C# BackgroundWorker & ManualResetEvent

2    17 Jun 2015 07:07 by u/periander

I'm trying to work out why calling this from a Form spins on the WaitOne indefinitely, but running it from the main function for example works fine:

var bgw = new BackgroundWorker();
var mre = new ManualResetEvent(false);
bgw.DoWork += (sender, args) => Thread.Sleep(1000);
bgw.RunWorkerCompleted += (sender, args) => mre.Set();
bgw.RunWorkerAsync();
mre.WaitOne();

Before you mention async & Task, I'm stuck with .NET 3.5 at the moment and just trying to understand why something isn't working as intended (too convoluted to explain), and this seems to be the root cause.

1 comment

0

Ok, so the WaitOne is blocking the RunWorkerCompleted from triggering. Have to Set the ManualResetEvent at the end of DoWork.

var bgw = new BackgroundWorker();
var mre = new ManualResetEvent(false);
bgw.DoWork += (s, a) => { Thread.Sleep(1000); mre.Set(); };
bgw.RunWorkerCompleted += (s, a) => { };
bgw.RunWorkerAsync();
mre.WaitOne();