1

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.

Pieter
  • 31,619
  • 76
  • 167
  • 242
  • possible duplicate of [Raising an Event between 2 threads when neither thread is a WinForm](http://stackoverflow.com/questions/4853351/raising-an-event-between-2-threads-when-neither-thread-is-a-winform) – Hans Passant Oct 21 '12 at 15:00

1 Answers1

0

I was able to get the RunWorkerCompleted handler to run on the the same thread by creating the instance of Foobar on a UI thread. Relevant snippet from this answer:

If the BackgroundWorker was created from the UI thread, then the RunWorkerCompleted event will also be raised on the UI thread.

Community
  • 1
  • 1
Pieter
  • 31,619
  • 76
  • 167
  • 242