涉及 TaskContinuationOptions.RunContinuationsAsynchronously 的奇怪案例

Strange case involving TaskContinuationOptions.RunContinuationsAsynchronously

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 的情况下,编写此代码是为了演示 async 方法的其余部分在 new Thread() 创建的线程上运行。然而,对于 System.Threading.Tasks.TaskContinuationOptions.RunContinuationsAsynchronously 它仍然以某种方式发现在新创建的线程中设置的特定 [ThreadStatic] 值(因此不能是 TaskScheduler 线程)并在 TrySetResult [=23 时立即清除=].

嘿嘿?这是怎么回事?

你应该通过 TaskCreationOptions.RunContinuationsAsynchronously,而不是 TaskContinuationOptions.RunContinuationsAsynchronously

传递 TaskContinuationOptions.RunContinuationsAsynchronously 将调用 overload that takes an object parameter,将其视为“状态”对象而不是控制 TCS 行为的标志。