C# – Update UI from multiple worker threads (.NET)

cmultithreadingnetuser interface

I have a pet project that I'm working on that has multiple worker threads. Outputting everything to the console is getting hard to follow, so I want to develop a UI that will have one output area per thread. I want to know the best way for the threads to send updates to the UI. I have two ideas:

1) Have each thread set a "DataUpdated" flag when new data is available, and have the UI periodically check for new data.

2) Create each thread with a callback to a UI Update(…) method to be called when new data becomes available.

I am currently leaning toward (2) for two reasons: I dislike the idea of "checking" each thread, and because this is my first multithreaded application and (2) seems simpler than it probably is. I want to know:

  • Which option is preferable in terms of simplicity and efficiency?
  • Do you have any tips for implementing (2) or something like it (i.e. more event-driven)?

Best Answer

You can easily implement (2) by creating BackgroundWorker components and doing the work in their DoWork handlers:

BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork += /* your background work here */;
bw.ProgressChanged += /* your UI update method here */;
bw.RunWorkerAsync();

Each BackgroundWorker can report progress to the UI thread by calling ReportProgress: although this is primarily designed for reporting progress on a bounded process, that's not mandatory -- you can pass your own custom data as well if that's what your UI update requires. You would call ReportProgress from your DoWork handler.

The nice thing about BackgroundWorker is that it takes care of a lot of messy cross-threading details for you. It also conforms to the event-driven model of updates which you (rightly) prefer to explicit callbacks.