BeginInvoke not supported on .NET core? (PlatformNotSupported Exception)
I have ported the FluentFTP library to .NET standard / .NET, but the async methods use BeginInvoke in the async / await block. So, something like this:
async ConnectAsync(){
BeginConnect();
}
void BeginConnect(){
BeginInvoke(...) << error at this point
}
At this point, I am getting a PlatformNotSupported exception. What can be done to support this in the .NET core?
- Full details here .
- Full code here: ConnectAsync , BeginConnect .
source to share
Asynchronous I / O methods should not be used Delegate.BeginInvoke
. This is providing a fake asynchronous wrapper for a synchronous method that needs to be asynchronous in the first place. The whole design needs to be re-evaluated.
.NET Core is not supportedDelegate.BeginInvoke
for very good reasons. It's possible that .NET Core 2.0 might decide to support them (because Microsoft IMO makes some bad design decisions with v2).
But back to the original problem: the solution is to do//TODO
: implement ConnectAsync
as a real asynchronous method. Then it's pretty easy to implement BeginConnect
and EndConnect
how to wraps around ConnectAsync
.
source to share
As @Steven Cleary says, the motivation for implementing a "true" asynchronous method is clear, but sometimes you have legacy code that you can't just make asynchronous. For those who need to keep the old interface: use Task.Run
. For example, when you had
IAsyncResult ar = someDelegate.BeginInvoke(state, null, null);
and use properties ar
to see when the task is complete, you're in luck, because the equivalent with tasks is:
Task task = Task.Run(() => someDelegate(state));
The good news is that the class Task
implements IAsyncResult
that you can recycle existing code. Later, when you find out that the delegate has finished, you could call
someDelegate.EndInvoke();
which is not supported by .NET Core. This can be replaced
task.Wait();
It will end up throwing exceptions that EndInvoke
your delegate is like EndInvoke
. This worked on our migration to .NET Core.
source to share