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

1

7

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).

Iquique answered 26/2, 2014 at 5:2 Comment(0)
H
2

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.

Haines answered 26/2, 2014 at 12:20 Comment(1)
I checked the .NET source code more thoroughly. Modifying the SynchronizationContext will modify the value stored in the execution context. I understand that execution context is not inherited for other jobs on the thread pool i.e. the thread pool uses the captured execution context of the caller of the other thread pool job, not the one used for the previous job, which modified it. Is that correct?Iquique

© 2022 - 2024 — McMap. All rights reserved.