返回线程使用时,线程池的await [英] Thread returning to thread pool when using await
问题描述
然而,随着的ASP.NET Web API中,如果您的请求进来在一个
线程,你等待的一些功能和呼叫ConfigureAwait(假)
这有可能把你当你是一个不同的线程
退回ApiController功能的最终结果。
块引用>
其实,只是在做一个
等待
可以做到这一点。一旦你的异步
方法打
一个等待
中,该方法被阻塞,但线程返回到线程
池。当方法是准备继续,任何线程被抢走
从线程池,并用于恢复方法
块引用><一个href=\"http://stackoverflow.com/questions/13489065/best-practice-to-call-configureawait-for-all-server-side-$c$c\">Source
我刚刚测试过,在一个控制台程序:
异步任务富()
{
INT Y = 0;
而(γ小于5)Y ++;
}异步任务testAsync()
{
INT I = 0;
而(ⅰ&小于100)
{
Console.WriteLine(异步前1:+ I +); }
等待美孚(); 而(I&LT; 105)
{
我++;
Console.WriteLine(异步1日后:+ I);
}
}调用
等待富()
不会引起testAsync
正在运行在返回线程池线程,testAsync
只是运行一行同一个线程从开始到结束就行。什么是我在这里丢失?解决方案
什么是我在这里丢失?
块引用>您缺少的编译器警告
警告CS1998这种异步方法缺乏'等待'经营者和将同步运行。考虑使用'等待'操作等待非阻塞API调用,或等待Task.Run(...)做在后台线程CPU绑定的工作。
块引用>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.Actually, just doing an
await
can do that. Once yourasync
method hits anawait
, the method is blocked but the thread returns to the thread pool. 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 threadtestAsync
was running on to return to thread pool,testAsync
just runs line by line on the same thread from start to end. 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. 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!