为什么要等待从异步方法返回一个任务都会被阻止? [英] Why waiting a task returned from async method gets blocked?
问题描述
我工作的一个南希/ ASP.Net项目。我试图用WebRequest的获取来自其他Web服务的数据和我实现了在一个异步函数的要求。我发现,当我尝试等待从函数返回一个任务,它就会无限期地封锁了问题。简化code看起来是这样的。
I'm working on a Nancy/ASP.Net project. I've tried to use WebRequest to get data from other web service and I've implemented the request in an async function. I find a problem that when I try to wait on a task returned from the function, it gets blocked indefinitely. The simplified code looks like this..
using System.Net;
using System.Threading.Tasks;
using Nancy;
public class TestModule : NancyModule{
public TestModule() {
Get["/"] = p => "Hello, world";
Get["/async/"] = p => {
var req = WebRequest.CreateHttp("http://localhost:13254/");
// var responseTask = req.GetResponseAsync(); // this works!
var responseTask = getResponse(req); // this gets blocked!
var waitSuccess = responseTask.Wait(10000);
return waitSuccess ? "Yeah!" : "woooh!";
};
}
async Task<HttpWebResponse> getResponse(HttpWebRequest request) {
return (HttpWebResponse) await request.GetResponseAsync();
}
}
在code使用NancyFx但它发生以及香草ASP.Net页面上。 localhost上的服务:13254工作正常。如果我使用)从申请的GetResponseAsync(直接返回任务,code工作正常,但如果我在异步方法包装它,它只是被阻止。
The code uses NancyFx but it happens as well on vanilla ASP.Net page. The service on localhost:13254 is working fine. If I use the task directly returned from request's GetResponseAsync(), the code works fine, but If I wrap it in an async method, it just gets blocked.
没有人有任何的想法有什么不对的code? :(我可以改变使用同步版本,但异步函数的作品在其他自托管服务发现...所以我想在这里使用相同的code太多,如果可能的。
Does anyone have any idea what's wrong with the code? :( I can change to use synchronous version but the async function works find in other self-hosting services... so I'd like to use the same code here too if possible..
推荐答案
I describe this deadlock behavior on my blog and in a recent MSDN article.
要解决这个问题,您可以使用 ConfigureAwait(假)
无处不在,也可以使用同步方法。该的理想的解决方案是使用等待
一路从不使用等待
或结果
,但可能不会在你的情况是可能的(如果南希工作异步它只会工作
代表,即获取[/异步/] =异步p =&GT; {...};
)
To fix this, you can either use ConfigureAwait(false)
everywhere, or you can use synchronous methods. The ideal solution is to use await
all the way and never use Wait
or Result
, but that may not be possible in your situation (it would only work if Nancy worked with async
delegates, i.e., Get["/async/"] = async p => { ... };
).
这篇关于为什么要等待从异步方法返回一个任务都会被阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!