简体   繁体   English

使用.NET 4.5基于任务的异步操作的WCF服务客户端,等待永远不会返回

[英]WCF Service Client with .NET 4.5 Task-Based Async Operations, await never returns

I've added a WCF service reference to my .NET 4.5 app, using the default "Generate task-based operations" option under "Allow Generation of asynchronous operations." 我已经使用“允许生成异步操作”下的默认“生成基于任务的操作”选项向我的.NET 4.5应用程序添加了WCF服务引用。 I'm calling the service from an async method of my own, sort of like so: 我是从我自己的异步方法调用服务,有点像这样:

public async Task<SomeData> GetDataAsync()
{
    var client = new MyServiceClient();
    var result = await client.GetSomeDataAsync();

    return result;
}

The await client.GetSomeDataAsync() never completes (a breakpoint on the return statement never gets hit) and I don't get a time out or any other error, no exception is thrown, nothing. await client.GetSomeDataAsync()永远不会完成(return语句中的断点永远不会被命中)并且我没有得到超时或任何其他错误,没有抛出异常,什么也没有。 Fiddler shows that the client sent the request and the service responded almost instantly with the expected data, so the problem is on my side of the fence somehow. Fiddler显示客户端发送了请求,服务几乎立即响应了预期的数据,所以问题就在我身边。

If I switch to the synchronous version instead 如果我切换到同步版本

var result = client.GetSomeData();

The call returns as expected. 该调用按预期返回。

What am I doing wrong? 我究竟做错了什么?

My chest hairs are tingling , Mr. T. I strongly suspect that further up your (client-side) call stack, you have some code that is calling Task<T>.Result or Task.Wait , which significantly increases the possibility of a deadlock (as I explain on my blog). 我的胸部发麻 ,T先生。我强烈怀疑你的(客户端)调用堆栈的进一步向上,你有一些代码调用Task<T>.Result Task.WaitTask.Wait ,这大大增加了死锁 (正如我在博客上解释的那样)。

By default, when you await a Task , the await will capture a "context" and use that to resume the async method. 默认情况下,当您await Taskawait将捕获“上下文”并使用它来恢复async方法。 If this is a context like a UI thread context, and then the code blocks the UI thread (ie, calling Result or Wait ), then the async method cannot resume on that UI thread. 如果这是像UI线程上下文这样的上下文,然后代码阻塞 UI线程(即,调用ResultWait ),则async方法无法在该UI线程上恢复。

I pity the fool who would attempt to mix synchronous and asynchronous code. 怜悯那些试图混合同步和异步代码的傻瓜 Just use async all the way (as I describe in an MSDN article). 只需一直使用async (正如我在MSDN文章中所描述的那样)。

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

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