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
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:
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;
}