我读了一些关于这个问题的文章,但我需要有人帮我澄清这一点,
public async Task<Person> Get()
{
//some code
var result= await AsyncFunction();
return result;
}
关于上面的代码,我理解的是,当代码执行命中await
时,当前线程转到线程池,当方法准备好继续时,任何线程都可以从线程池中选择继续方法执行。这是真的还是假的? await
之前的线程与 'await' 之后的线程是否相同?
如果我使用ConfigureAwait(false)
,它会导致选择不同的线程来执行代码吗?或者与线程跳转无关?
最佳答案
我建议阅读我的async
intro .
When the method is ready to continue, any thread may choose from thread pool to continue method execution. is it true or not? the thread before await is same to after 'await' or not?
在 ASP.NET 中,是的,确实如此。任何可用的线程池线程都可以在 await
之后恢复执行该方法。
if i use ConfigureAwait(false) it cause to choose different thread for execution code? or it's not related to thread jump?
实际发生的情况是,await
默认情况下将捕获其当前的“上下文”。在 ASP.NET Core 上,没有要捕获的上下文,因此 await
使用线程池上下文。在 ASP.NET pre-Core 上,有一个 SynchronizationContext.Current
值被捕获并用于恢复执行该方法。 ASP.NET(Core 之前)SynchronizationContext
可以使用任何线程池线程;它只是为了确保某些内容被复制,最值得注意的是 HttpContext.Current
。
如果您使用ConfigureAwait(false)
,那么这就告诉await
不捕获当前上下文。在 ASP.NET Core 上,这没有任何效果,因为无论如何都没有上下文可供捕获。在 ASP.NET pre-Core 上,这将导致该方法在线程池线程上恢复执行,但不使用 SynchronizationContext
,因此 HttpContext.Current
在 await
之后不可用。
关于c# - Asp.net Web应用程序中await后哪个线程恢复方法执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57295669/