BeginInvoke not supported on .NET core? (PlatformNotSupported exception)
Asynchronous I/O methods should not use Delegate.BeginInvoke
. That's exposing a fake-asynchronous wrapper for a synchronous method that should be asynchronous in the first place. The whole design needs re-evaluation.
.NET Core does not support Delegate.BeginInvoke
for very good reasons. It's possible that .NET Core 2.0 may decide to support them (because Microsoft IMO is making some poor design decisions with v2).
But back to the original problem: the solution is to do the //TODO
: implement ConnectAsync
as a true asynchronous method. Then it's pretty straightforward to implement BeginConnect
and EndConnect
as wrappers around ConnectAsync
.
The motivation for implementing a "true" async method is clear, as stated by @Steven_Cleary, but sometimes you have legacy code you cannot simply make async. For those in desperate need for keeping the old interface: Use Task.Run
. E.g. when you had
IAsyncResult ar = someDelegate.BeginInvoke(state, null, null);
and use properties of ar
in order to see when the task is finished, you are in luck because the equivalent with Tasks is:
Task task = Task.Run(() => someDelegate(state));
The good news is that the Task
class implements IAsyncResult
such that you can recycle your existing code.
Later when you know the delegate has finished, you might have called
someDelegate.EndInvoke();
which is neither supported by .NET Core. This can the be replaced by
task.Wait();
It eventually throws exceptions your delegate has thrown, just like EndInvoke
.
This worked in our migration to .NET Core.