0
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返回后立即清除。

什么嘿?这是怎么回事?

4

1 回答 1

3

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

传递TaskContinuationOptions.RunContinuationsAsynchronously将调用带有参数的重载,object将其视为“状态”对象而不是控制 TCS 行为的标志。

于 2021-05-07T20:09:46.783 回答