views:

68

answers:

2

This is a pretty basic question, and I imagine that it is, but I can't find any definitive answer. Is SynchronizationContext.Post() threadsafe?

I have a member variable which holds the main thread's context, and _context.Post() is being called from multiple threads. I imagine that Post() could be called simultaneously on the object. Should I do something like

lock (_contextLock) _context.Post(myDelegate, myEventArgs);

or is that unnecessary?

Edit:
MSDN states that "Any instance members are not guaranteed to be thread safe." Should I keep my lock(), then?

+3  A: 

Going strictly off the MSDN documentation then no, the SynchronizationContext.Post method is not thread-safe. So unless there is an error in the documentation then you will need to synchronize access to the method. I find hard to believe that it is not thread-safe myself, but you cannot bank on assumptions especially when dealing with thread synchronization issues. There really is no way around this until Microsoft either corrects the documentation or truly makes it thread-safe.

Brian Gideon
Looking at the disassembled code this method just calls ThreadPool.QueueUserWorkItem which, according to msdn, IS thread safe.
Phil Lamb
@Phil: That is not surprising. Unfortunately Microsoft has effectively reserved the right to change the implementation in a way that would void its current thread-safe behavior in a future release or service pack. My guess is that they really did intend for that class to have thread-safe instance methods and that they just screwed up the documentation. But, again, that is just an assumption.
Brian Gideon
Given its usage it would be silly for them to change it to not be thread safe!
RichardOD
@RichardOD: I totally agree! They really need to fix the documentation. And this isn't the only instance needing to be fixed either.
Brian Gideon
+1  A: 

SynchronizationContext.Post is threadsafe. The documentation has overlooked this fact.

I base this assertion on Microsoft's implementations of AsyncOperation and AsyncOperationManager, which assume SynchronizationContext.Post is threadsafe (including any derived implementations).

Stephen Cleary