[英]Thread returning to thread pool when using await
However, with ASP.NET Web Api, if your request is coming in on one thread, and you await some function and call
ConfigureAwait(false)
that could potentially put you on a different thread when you are returning the final result of your ApiController function. 但是,对于ASP.NET Web Api,如果您的请求正在一个线程中发出,并且您等待某个函数并调用ConfigureAwait(false)
,则当您返回ApiController函数的最终结果时,这有可能使您进入另一个线程。Actually, just doing an
await
can do that. 实际上,只需await
即可。 Once yourasync
method hits anawait
, the method is blocked but the thread returns to the thread pool. 一旦您的async
方法达到await
,该方法将被阻止,但线程将返回线程池。 When the method is ready to continue, any thread is snatched from the thread pool and used to resume the method. 当该方法准备好继续时,将从线程池中抢夺任何线程,并将其用于恢复该方法。
I've just tested that in a console program: 我刚刚在控制台程序中进行了测试:
async Task foo()
{
int y = 0;
while (y<5) y++;
}
async Task testAsync()
{
int i = 0;
while (i < 100)
{
Console.WriteLine("Async 1 before: " + i++);
}
await foo();
while (i < 105)
{
i++;
Console.WriteLine("Async 1 after: " + i);
}
}
Calling await foo()
doesn't cause the thread testAsync
was running on to return to thread pool, testAsync
just runs line by line on the same thread from start to end. 调用await foo()
不会导致正在运行线程testAsync
返回线程池,而testAsync
只是testAsync
在同一线程上testAsync
运行。 What's am I missing here? 我在这里想念什么?
What's am I missing here? 我在这里想念什么?
You are missing compiler warnings 您缺少编译器警告
Warning CS1998 This async method lacks 'await' operators and will run synchronously. 警告CS1998此异步方法缺少“等待”运算符,将同步运行。 Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. 考虑使用“ await”运算符来等待非阻塞API调用,或者使用“ await Task.Run(...)”来在后台线程上执行CPU绑定的工作。
The method foo
isn't really asynchronous as there are no await
calls in it. foo
方法并不是真正的异步方法,因为其中没有await
调用。
Try adding await Task.Delay
in there. 尝试在其中添加await Task.Delay
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.