Search code examples
c#multithreadingbackgroundworker

Waiting for backgroundworker


I have two methods which do some work by using BackgrounderWorker. If i run first method then it does some work in background and same goes for second method. But what I want is that second method should wait untill method one worker is started.

Code

private void Method1(object sender, RoutedEventArgs e)
{
    RunFirstWorker();
}

private void Method2(object sender, RoutedEventArgs e)
{
    RunFirstWorker();
    RunSecondWorker();
}

Solution

  • You could use event object (ManualResetEvent or AutoResetEvent) to synchronise execution of these functions. Create the event in non-signalled state and wait for it at the beginning of RunSecondWorker()'s DoWork event handler. Set the state of this event to signalled at the end of RunFirstWorker()'s DoWork event handler.

    In your original code snippet Method1() and Method2() were GUI callbacks (methods executed on the GUI thread) so you don't want to block them (you don't want to wait for event in any of those methods themselves but in BackgroundWorker callback - DoWork event handler).