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

标签 c# .net web-services

我正在从 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/

相关文章:

java - 如何根据传入的 ROOT 请求动态更改 web.xml 中的欢迎文件

c# - 如何为我的应用程序实现触摸事件?

c# - 无法加载类型 'newVersion_Default'

C# 转换泛型(协变和逆变?)

.net - IIS6 上的 ASP.NET MVC

mysql - 构建 API 时 Grails 默认时区性质

c# - Static 和 Const 字段的内存消耗

javascript - 从 MVC 下载文件

c# - 聚合 RSS 阅读器因 XML 无效而失败?

java - Web 服务版本控制和服务器端处理