[英]The web server hangs while calling 3rd party Web API from my Web API
I need to call a 3 party Web Api from my ASP.net Web API, when it runs the line 当我运行该行时,我需要从我的ASP.net Web API调用3方Web Api
HttpResponseMessage response = await client.PostAsJsonAsync("api/ArTrx/postDocument", poMaster);
the web server hangs. Web服务器挂起。 I have tried to put below code in to a console program, it runs well.
我试图将下面的代码放入控制台程序,它运行良好。 What is wrong with below code when run in ASP.net Web API project?
在ASP.net Web API项目中运行时,下面的代码有什么问题?
client.BaseAddress = new Uri(webAPIAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string token = Crypto.EncryptStringAES("abcd1234");
client.DefaultRequestHeaders.Add("X-Token", token);
HttpResponseMessage response = await client.PostAsJsonAsync("api/ArTrx/postDocument", poMaster);
if (response.IsSuccessStatusCode)
{
...
}
You probably have a Task<T>.Result
or Task.Wait
call further up your call stack. 您可能有一个
Task<T>.Result
Task.Wait
或Task.Wait
进一步调用您的调用堆栈。 This will cause a deadlock on ASP.NET that I describe in more detail on my blog. 这将导致我在我的博客上更详细描述的ASP.NET死锁 。
In summary, await
will capture a "context" - in this case, an ASP.NET request context, which only allows one running thread at a time. 总之,
await
将捕获一个“上下文” - 在本例中是一个ASP.NET请求上下文,它一次只允许一个正在运行的线程。 When its awaitable completes (that is, when the POST finishes), the async
method will continue in that context . 当等待完成时(即POST结束时),
async
方法将在该上下文中继续。 If your code is blocking further up the call stack (eg, Result
or Wait
), then it will block a thread in that ASP.NET request context, and the async
method cannot enter that context to continue executing. 如果您的代码阻塞了调用堆栈(例如,
Result
或Wait
),那么它将阻止该ASP.NET请求上下文中的线程,并且async
方法无法进入该上下文以继续执行。
You don't see the deadlock in the Console app because there's no context being captured, so the async
method resumes on a thread pool thread instead. 您没有在控制台应用程序中看到死锁,因为没有捕获上下文,因此
async
方法在线程池线程上恢复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.