March 6, 2008

Simple Background Worker Object Template

BackgroundWorker backgroundWorker
Worker worker;

private void AsyncStartWork()
{
    if (!backgroundWorker.IsBusy)
    {
        worker = new Worker(...);
        backgroundWorker.DoWork += new
 DoWorkEventHandler(backgroundWorker_DoWork);
        backgroundWorker.RunWorkerCompleted += new
 RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
        backgroundWorker.RunWorkerAsync((object)worker);
    }
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    Worker worker = e.Argument as Worker;
    if (worker != null)
    {
        worker.DoSomething();
    }
}

private void backgroundWorker_RunWorkerCompleted(object sender,
 RunWorkerCompletedEventArgs e)
{
    backgroundWorker.DoWork -= new
 DoWorkEventHandler(backgroundWorker_DoWork);
    backgroundWorker.RunWorkerCompleted -= new
 RunWorkerCompletedEventHandler(
        backgroundWorker_RunWorkerCompleted);

    // Update GUI

    // IF necessary do something with results
    Show(worker.Results);
}

No comments: