async void Main()
{
T0.TT();
}
private class T0
{
[ThreadStatic] private static int test;
public static async void TT()
{
test = 4;
var continuation = new System.Threading.Tasks.TaskCompletionSource<int>(System.Threading.Tasks.TaskContinuationOptions.RunContinuationsAsynchronously);
var th = new Thread(() => { Thread.Sleep(500); Console.WriteLine(test); test = 3; continuation.TrySetResult(5); test = 7; });
th.Start();
Console.WriteLine(await continuation.Task);
Console.WriteLine(test);
}
}
Output:
0
5
3
因此,如果没有System.Threading.Tasks.TaskContinuationOptions.RunContinuationsAsynchronously
编写 this 来演示该async
方法的其余部分在由new Thread()
. 然而,System.Threading.Tasks.TaskContinuationOptions.RunContinuationsAsynchronously
它仍然以某种方式找到[ThreadStatic]
在新创建的线程中设置的特定值(因此不能是 TaskScheduler 线程)并在TrySetResult
返回后立即清除。
什么嘿?这是怎么回事?