【发布时间】:2020-04-26 05:36:38
【问题描述】:
.NET 是在新的不同线程池线程上恢复等待继续,还是重用之前恢复的线程?
让我们在下面的 .NET Core 控制台应用程序中绘制 C# 代码:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NetCoreResume
{
class Program
{
static async Task AsyncThree()
{
await Task.Run(() =>
{
Console.WriteLine($"AsyncThree Task.Run thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
});
Console.WriteLine($"AsyncThree continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static async Task AsyncTwo()
{
await AsyncThree();
Console.WriteLine($"AsyncTwo continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static async Task AsyncOne()
{
await AsyncTwo();
Console.WriteLine($"AsyncOne continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static void Main(string[] args)
{
AsyncOne().Wait();
Console.WriteLine("Press any key to end...");
Console.ReadKey();
}
}
}
它会输出:
AsyncThree Task.Run thread id:4
AsyncThree continuation thread id:4
AsyncTwo continuation thread id:4
AsyncOne continuation thread id:4
Press any key to end...
我尝试在每次等待Task 之后添加ConfigureAwait(false),但会得到相同的结果。
正如我们所见,似乎所有的 await 延续都重用了在 Task.Run 的 AsyncThree() 方法中创建的线程。
我想问一下.NET 是否总是会在先前的恢复线程上恢复等待继续,或者它会在某些情况下从线程池应用一个新的不同线程?
我知道在下面的讨论中会在线程池线程上继续继续:
async/await. Where is continuation of awaitable part of method performed?
让我们排除上面链接中的SynchronizationContext 案例,因为我们现在讨论的是.NET 控制台应用程序。但是我想问一下好像那个线程池线程在我的例子中总是thread id 4,我不知道是不是因为thread id 4在线程池中总是空闲的,所以每个continuation 重用是巧合,还是 .NET 有机制会尽可能重用之前的恢复线程?
每个延续是否有可能在不同的线程池线程上恢复,如下所示?
AsyncThree Task.Run thread id:4
AsyncThree continuation thread id:5
AsyncTwo continuation thread id:6
AsyncOne continuation thread id:7
Press any key to end...
【问题讨论】:
-
我希望在返回调用堆栈时使用相同的线程,因此最后 3 个输出报告相同的线程我并不感到惊讶。
-
@spender 当然,我也希望如此......但我只想知道等待延续是否会随机从线程池中获取一个线程,或者 .NET 具有优先级将恢复以某种方式延续之前的恢复线程?
-
您问是因为您担心原始线程的内存写入对后续线程可见吗?我一直认为
awaitcontinuation 引入了一个happens-before 障碍,因为如果不这样做会非常错误。但我无法指出它所做的任何文档。 -
@user560822:没有记录,但微软人员向我保证,如果
await导致线程切换,障碍总是存在的。
标签: c# multithreading asynchronous async-await