I have an external library which has a method which performs a long running task on a background thread. When it's done it fires off a Completed event on the thread that kicked off the method (typically the UI thread). It looks like this:
public class Foo
{
public delegate void CompletedEventHandler(object sender, EventArgs e);
public event CompletedEventHandler Completed;
public void LongRunningTask()
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(5000);
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Completed != null)
Completed(this, EventArgs.Empty);
}
}
The code that calls this library looks like this:
private void button1_Click(object sender, EventArgs e)
{
Foo b = new Foo();
b.Completed += new Foo.CompletedEventHandler(b_Completed);
b.LongRunningTask();
Debug.WriteLine("It's all done");
}
void b_Completed(object sender, EventArgs e)
{
// do stuff
}
In the button1_Click method, after I call b.LongRunningTask(), the Completed event fires off 5 seconds later on the UI thread, I update the UI and everything is great, since I don't have to deal with marshaling stuff to the proper thread.
However, I now have a need for the process to be synchronous (without changing the external library). In other words, after I kick off .LongRunningTask method, the next meaningful statement in that method should fire after .LongRunningTask has completed.
I've tried doing it with the EventWaitHandle (e.g. doing WaitOne after the call to LongRunningTask and then Resetting it in the Completed event, but that just locks everything up).
Is there a method in the .NET framework that allows me to do this?