Thread returning to thread pool when using await

 ̄綄美尐妖づ 提交于 2019-12-20 07:18:08

问题


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 your async method hits an await, 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.

Source

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. What's am I missing here?


回答1:


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.




回答2:


The method foo isn't really asynchronous as there are no await calls in it.
Try adding await Task.Delay in there.



来源:https://stackoverflow.com/questions/33711136/thread-returning-to-thread-pool-when-using-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!