In this post I wanted to briefly discuss using the ManualResetEvent with BackgroundWorker threads. I often find myself using BackgroundWorkers to perform processing of data without locking up the user interface for a user. Occasionally, I have UI tasks that would need to continue only after the background processing has completed. Instead of wiring up completion events, I often find it easier to simply use a ManualResetEvent to signal back when I can continue processing on the calling thread.
ManualResetEvent mre = new ManualResetEvent(false); BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += (obj, ea) => { //Do background work here for (int i = 0; i < (100 * 1000); i++) { Trace.WriteLine("On line: " + i.ToString()); } //Escalate back to UI thread this.BeginInvoke((MethodInvoker)delegate { lbl_Status.Text = "Complete"; }); //Signal that we can continue mre.Set(); }; bw.RunWorkerAsync(); mre.WaitOne(); //wait until the thread completes and signals we can continue return true;
In the C# .NET example above, a BackgroundWorker thread is kicked off asynchronously and then the calling thread waits to return true until the ManualResetEvent has been signaled (set). This is a very arbitrary example, but it shows how the MRE can easily work across threads enabling you to effectively ‘pause’ your code until the parallel event completes. Sound off in the comments with questions and feedback.
Leave a Reply