using ThreadStatic variables with async/await

后端 未结 5 996
独厮守ぢ
独厮守ぢ 2020-12-08 19:21

With the new async/await keywords in C#, there are now impacts to the way (and when) you use ThreadStatic data, because the callback delegate is executed on a different thre

5条回答
  •  孤街浪徒
    2020-12-08 20:19

    Basically, I would emphasize: don't do that. [ThreadStatic] is never going to play nicely with code that jumps between threads.

    But you don't have to. A Task already carries state - in fact, it can do it 2 different ways:

    • there's an explicit state object, which can hold everything you need
    • lambdas/anon-methods can form closures over state

    Additionally, the compiler does everything you need here anyway:

    private static async Task Start()
    {
        string secret = "moo moo";
        Console.WriteLine("Started on thread [{0}]",
            Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("Secret is [{0}]", secret);
    
        await Sleepy();
    
        Console.WriteLine("Finished on thread [{0}]",
            Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("Secret is [{0}]", secret);
    }
    

    No static state; no issues with threads or multiple tasks. It just works. Note that secret is not just a "local" here; the compiler has worked some voodoo, like it does with iterator blocks and captured variables. Checking reflector, I get:

    [CompilerGenerated]
    private struct d__0 : IAsyncStateMachine
    {
        // ... lots more here not shown
        public string 5__1;
    }
    

提交回复
热议问题