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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With