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 SynchronizationCon开发者_Python百科text.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 mylock()
, then?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.
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).
精彩评论