I have an instance of class Foobar
that was constructed on thread X. I have a function StartWork()
that should only be called from thread X. To avoid creating bugs I enforce this constraint by checking Debug.Assert(CreatorID == Environment.CurrentManagedThreadId)
. The function starts the asynchronous operation of a BackgroundWorker
. I've ensured that WorkCompleted()
is called when the worker finishes its operations by hooking into RunWorkerCompleted
.
For thread safety reasons WorkCompleted()
should be executed on thread X, since it sends out event notifications. If these notifications are broadcast from the wrong thread, the program might run into unforeseen thread safety issues, I presume.
However, in my tests I noticed that WorkCompleted()
isn't called from thread X as I expected. How can I fix my program to prevent any thread safety issues that may arise from these events being raised? Am I approaching the problem incorrectly? I'm already aware of the fact that I'll still need to make my BackgroundWorker.DoWork
handler thread-safe.