C# .NET core上不支持BeginInvoke?(PlatformNotSupported异常)
我已将库FluentFTP移植到.NET standard/.NET core,但异步方法在异步/等待块中使用BeginInvoke。所以是这样的:C# .NET core上不支持BeginInvoke?(PlatformNotSupported异常),c#,asynchronous,cross-platform,.net-core,C#,Asynchronous,Cross Platform,.net Core,我已将库FluentFTP移植到.NET standard/.NET core,但异步方法在异步/等待块中使用BeginInvoke。所以是这样的: async ConnectAsync(){ BeginConnect(); } void BeginConnect(){ BeginInvoke(...) << error at this point } async ConnectAsync(){ BeginConnect(); } void BeginConnect
async ConnectAsync(){
BeginConnect();
}
void BeginConnect(){
BeginInvoke(...) << error at this point
}
async ConnectAsync(){
BeginConnect();
}
void BeginConnect(){
BeginInvoke(…)异步I/O方法不应使用委托。BeginInvoke
。这暴露了同步方法的一个缺陷,而同步方法首先应该是异步的。整个设计需要重新评估
有很好的理由。可能.NET Core 2.0会决定支持它们(因为Microsoft IMO在v2上做出了一些糟糕的设计决策)
但回到最初的问题:解决方案是:将ConnectAsync
实现为真正的异步方法。然后将BeginConnect
和EndConnect
实现为ConnectAsync
的包装,这是实现“真正”的动机async方法很明确,正如@Steven_Cleary所说,但有时您的遗留代码不能简单地使其异步。对于那些迫切需要保留旧接口的人:使用任务。运行。例如,当您
IAsyncResult ar = someDelegate.BeginInvoke(state, null, null);
并使用ar
的属性查看任务何时完成,您很幸运,因为任务的等价物是:
Task task = Task.Run(() => someDelegate(state));
好消息是任务
类实现了IAsyncResult
,这样您就可以回收现有的代码。
稍后,当您知道代理已完成时,您可能会打电话
someDelegate.EndInvoke();
它既不受.NET Core支持,也不受.NET Core支持。可以用
task.Wait();
它最终抛出委托抛出的异常,就像EndInvoke
。
这在我们迁移到.NETCore的过程中起了作用