.Net BackgroundWorker class

The BackgroundWorker class is an easy way to start up a thread from the GUI to run some lengthy action in the background.  Key points are:

  • The DoWork event runs on the background thread.  You can’t interact with the GUI from there.  The ProgessChanged and RunWorkerCompleted events are raised by the background thread into the GUI thread, so that you can interact with the GUI.
  • In the DoWork event, the MSDN example tells you:
    // Do not access the form’s BackgroundWorker reference directly.
    // Instead, use the reference provided by the sender parameter.
    BackgroundWorker bw = (BackgroundWorker)sender;

    Is that just because you might use the same event for multiple threads, or is there some other reason?

  • You can run multiple background threads.
  • Question:  What is the best way to debug possible problems with the background threads?  We can use SystInternals ProcMon to see when the thread was started and exited.  We can write to event logs.  What else?

Post a Comment

Required fields are marked *

%d bloggers like this: