Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is SynchronizationContext.Current reset when a thread goes back to threadpool

Let's say I have this code

ThreadPool.QueueUserWorkItem(unused => 
    {
        SynchronizationContext.SetSynchronizationContext(
            new MyCustomSynchronizationContext());

        // not reset back to null
    }, null);

The current synchronization context is leaked back to thread pool. If someone calls ThreadPool.QueueUserWorkItem again and the same thread is used to process the other work item, will the current synchronization context of that thread be reset back to null or will it stay MyCustomSynchronizationContext?

Does the same answer apply to any other way for executing tasks on the thread pool e.g. Task.Run, BeginInvoke, etc.?

I know that in general the TLS is not reset but .NET source code shows that the storage of the current synchronization context is not very clearly defined (most of the time it comes from the executioncontext but it seems to be special cased for WinRT for some reason).

like image 381
Palo Avatar asked Nov 02 '22 04:11

Palo


1 Answers

The answer is technically undefined/undocumented. You're not supposed to put a SynchronizationContext on a thread pool thread without cleaning it up.

That said, I strongly suspect that SynchronizationContext is not cleared. This would be true for any code that executes tasks on the thread pool.

like image 132
Stephen Cleary Avatar answered Nov 15 '22 05:11

Stephen Cleary