gpt4 book ai didi

c# - 异步 Web 服务调用是否始终调用 AsyncCallback?

转载 作者:太空宇宙 更新时间:2023-11-03 19:37:28 27 4
gpt4 key购买 nike

我正在从 C# 应用程序进行异步网络服务调用:

{
//Put UI in 'loading' state
...

//Now call web service
webServiceProxy.BeginMyMethod(param, new AsyncCallback(MyCallback), null);
}


private void MyCallback(IAsyncResult res)
{
...
//process result

// Put UI back in normal state (yes I'm marshalling back to the UI thread)
}

主线程将应用程序置于“等待”模式,然后回调函数结束重新启用控件。我偶尔会看到一个错误,即 UI 永远停留在加载模式。

现在回调代码中可能只有一个错误(那里有很多错误),但我在这里向社区提出的问题是:

是否保证调用“MyCallback”?假设“BeginMyMethod”没有抛出异常,我能确定 MyCallback 会被执行吗?我在 BeginXXX 函数返回的 IAsyncResult 上看到“CompletedSynchronously”和“IsCompleted”,但我不确定这是否重要。

最佳答案

是的,保证调用回调。回调允许使用 Begin*/End* 模式的异步代码以连续传递样式编写。

但是,您必须在回调中调用相应的 End* 方法(通常是回调中的第一件事)。它是异步方法如何发出调用期间可能发生的异常的信号,一方面,也是获取结果(如果有)的方式。

使用 C# 2.0 时使用匿名委托(delegate)编写异步模式有时更优雅,并且允许在接近调用启动时编写调用后延续,并允许通过捕获的变量更轻松地共享数据,前提是使用适当的同步措施。

引用: http://msdn.microsoft.com/en-us/library/ms228972.aspx :

Applications that can do other work while waiting for the results of an asynchronous operation should not block waiting until the operation completes. Use one of the following options to continue executing instructions while waiting for an asynchronous operation to complete:

  • Use an AsyncCallback delegate to process the results of the asynchronous operation in a separate thread. This approach is demonstrated in this topic.

[...]

关于c# - 异步 Web 服务调用是否始终调用 AsyncCallback?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/635730/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com