.Net core & SynchronizationContext & Thread.SetData

I was surprised because I believe that SetData was part of the synchronization context. (which should not exist in asp.net core)

No; SetData is thread-local storage (TLS). So it's tied to a specific thread. This doesn't have anything to do with synchronization contexts.

More, when I used ConfigureAwait(false) , I got null in res.

Depending on when you run this code, how busy the server is, etc., you could get null or 4 with or without ConfigureAwait(false).

If asp.net core doesn't have a SynchronizationContext, then why did 4 was available after await ?

It's a thread-specific value. There's no SynchronizationContext on ASP.NET Core, and your code will resume on any available thread pool thread. If that thread happens to be the same thread that started that method, then the TLS is going to still be there because it's for that specific thread.

The same behavior actually applies to ASP.NET pre-Core. In that case, there is a SynchronizationContext, but that context isn't tied to any particular thread. Just like ASP.NET Core, asynchronous methods on ASP.NET pre-Core can resume on any available thread pool thread, so TLS data may or may not be there after an await.

To support this theory with data, try logging Environment.CurrentManagedThreadId before and after the await and see if there's any correlation between the data being present and the id remaining the same.


You're invoking SetData on Thread. How come you thought it was part of SynchronizationContext.

You can easily test if there's a current SynchronizationContext by checking the value of SynchronizationContext.Current- If it's null, then there's no SynchronizationContext.

How many concurrent requests did you issued to test that code?

SynchronizationContext or not the way the framework/runtime flows the context (like in types like AsyncLocal<T>) is through the ExecutionContext data, not Thread data.