I have a console application. A class (let’s say Worker) does some work in a separate thread and throws an event when it finishes. But this never happens because the execution ends instantly. How can I wait for the thread to finish and handle the event after it throws?
static void Main(string[] args) { Worker worker = new Worker(); worker.WorkCompleted += PostProcess; worker.DoWork(); } static void PostProcess(object sender, EventArgs e) { // Cannot see this happening }
Edit: Corrected the order of the statements but that was not the problem.
You’ve got a race condition, in that the work could finish before you register for the event. To avoid the race condition, change the order of the code so you register for the event before starting the work, then it will always be raised, no matter how fast it finishes:
Edit:
OK the question has been modified, so it looks like what you’re really asking is how to wait for
PostProcessto finish executing. There are a couple of ways to do this, but you’ll have to add some more code.The easiest way is, because events always execute on the same thread as they are raised, is to call
Thread.Joinon the thread theWorkerclass creates, e.g. assuming the thread is exposed as a property:(Although to be honest I’d probably keep the
Threadprivate and expose a method called something likeWaitForCompletionon theWorkerclass that calls it).Alternative methods are:
Have a
WaitHandle, probably aManualResetEvent, in theWorkerclass which isSetwhen it completes all its work, and callWaitOneon it.Have a
volatile bool completefield in theWorkerclass and loop while waiting for it to be set totrue, usingThread.Sleepin the loop body (this probably isn’t a good solution, but it is feasible).There are probably other options too, but that’s the common ones.