dlras2
dlras2

Reputation: 8496

Is SynchronizationContext.Post() threadsafe?

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?

Upvotes: 2

Views: 711

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 457117

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

Upvotes: 2

Brian Gideon
Brian Gideon

Reputation: 48959

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.

Upvotes: 3

Related Questions