BeginInvoke not supported on .NET core? (PlatformNotSupported exception)

梦想的初衷 提交于 2021-02-07 11:17:44

问题


I've ported a library FluentFTP to .NET standard/.NET core but the async methods use BeginInvoke within an async/await block. So its something like this:

async ConnectAsync(){
   BeginConnect();
}
void BeginConnect(){
   BeginInvoke(...)   << error at this point
}

At that point I get a PlatformNotSupported exception. What can be done to support this on .NET core?

  • Full info here.
  • Full code here: ConnectAsync, BeginConnect.

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/45183294/begininvoke-not-supported-on-net-core-platformnotsupported-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!