简体   繁体   English

WCF客户端阻止异步方法

[英]WCF client blocks on async methods

I'm working on WCF client app, and I facing difficulties with the await/async pattern. 我正在使用WCF客户端应用程序,我遇到了await / async模式的困难。 It seems that the line: await client.LongOperationAsync(); 似乎行: await client.LongOperationAsync(); always blocks. 总是块。 As I understand, the thread supposed to exit and continue on to the Main() method and then return when the async method completes, maybe I'm wrong. 据我所知,该线程应该退出并继续到Main()方法,然后在异步方法完成时返回,也许我错了。

The output for the code below is (always): 下面代码的输出是(总是):

Test() started Test()开始了
Test() error Test()错误
* *
* *
* *
... ...

The Test() method always completes before the context returns to main. Test()方法总是上下文返回main 之前完成。 Any thoughts would be highly appreciated. 任何想法都将受到高度赞赏。

 static void Main(string[] args) { Program p = new Program(); p.Test(); while (true) { Console.WriteLine("*"); Thread.Sleep(500); } } private async Task Test() { Console.WriteLine("Test() started"); try { MySoapClient client = new MySoapClient( new BasicHttpBinding(new BasicHttpSecurityMode()), new EndpointAddress("http://badaddress")); await client.LongOperationAsync(); Console.WriteLine("Test() success"); } catch (Exception) { Console.WriteLine("Test() error"); return; } Console.WriteLine("Test() end successfully"); } 

Async methods execute synchronously until the first await ; 异步方法同步执行,直到第一个await ; if your LongOperationAsync method performs a blocking operation before its first await, the calling method will be blocked as well. 如果您的LongOperationAsync方法在第一次等待之前执行阻塞操作,则调用方法也将被阻止。 I suspect that's what happening in your case. 我怀疑这是你的情况。

This is probably because WebRequest.BeginGetResponse performs some of its work synchronously. 这可能是因为WebRequest.BeginGetResponse同步执行某些工作。 See Stephen Toub's answer to this question : 请参阅Stephen Toub 对此问题的回答:

The Async CTP's GetRequestStreamAsync and GetResponseAsync are simple wrappers around the existing HttpWebRequest.BeginGetRequestStream and BeginGetResponse in .NET 4. Those Begin* methods have a lot of setup work they do (eg proxy, DNS, connection pooling, etc.) before they can submit a request, and unfortunately today that work all happens synchronously as part of the Begin* call. Async CTP的GetRequestStreamAsync和GetResponseAsync是围绕.NET 4中现有HttpWebRequest.BeginGetRequestStream和BeginGetResponse的简单包装器。这些Begin *方法在提交之前有很多设置工作(例如代理,DNS,连接池等)一个请求,不幸的是今天所有工作都是作为Begin *调用的一部分同步发生的。

In this case, you provided a bad domain name, so I suspect it takes a while for the DNS resolution to fail. 在这种情况下,您提供了一个错误的域名,因此我怀疑DNS解析失败需要一段时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM