Skip to main content
 首页 » 编程设计

c#之在 Asp.net Web 应用程序中等待后哪个线程恢复方法执行

2024年02月04日25jpfss

我读了一些关于这个问题的文章,但我需要有人为我澄清一下,

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(pre-Core)SynchronizationContext 可以使用任何线程池线程;它只是为了确保复制某些内容,最显着的是 HttpContext.Current。

如果您使用 ConfigureAwait(false),则告诉 await 不 捕获当前上下文。在 ASP.NET Core 上,这没有任何效果,因为无论如何都没有要捕获的上下文。在 ASP.NET pre-Core 上,这将导致该方法在线程池线程上恢复执行,但不使用SynchronizationContext,因此HttpContext.Current 在 await 之后不可用。