Craig Johnston
Craig Johnston

Reputation: 7607

C#: how to do basic BackgroundWorkerThread

Let's say I have the following function in C#:

void ProcessResults()
{  
    using (FormProgress f = new FormProgress()) {
        f.ProgressAmount = 10;
        // I want to have the following line run in a BackgroundWorkerThread
        RetrieveAndDisplayResults();
        f.ProgressAmount = 100;
    }
}

What would I need to do for the line RetrieveAndDisplayResults(); to be run in a BackgroundWorkerThread?

Upvotes: 2

Views: 121

Answers (3)

madd0
madd0

Reputation: 9323

You will probably have to change your approach, but the code below should be able to give a scaffolding for a long-running task that updates the UI as it progresses:

private void LaunchWorker()
{
    var worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(OnDoWork);
    worker.ProgressChanged += new ProgressChangedEventHandler(OnProgressChanged);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnRunWorkerCompleted);

    worker.RunWorkerAsync();
}

void OnDoWork(object sender, DoWorkEventArgs e)
{
    var worker = sender as BackgroundWorker;

    while (aLongTime)
    {
        worker.ReportProgress(percentageDone, partialResults);
    }

    e.Result = results;
}

void OnProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var progress = e.ProgressPercentage;
    var partialResults = e.UserState;

    // Update UI based on progress
}

void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var results = e.Result;

    // Do something with results
}

Upvotes: 1

Ray
Ray

Reputation: 46595

var f = new FormProgress()

f.ProgressAmount = 10;
var worker = new BackgroundWorker();
worker.DoWork += (o, e) => RetrieveAndDisplayResults();
worker.RunWorkerCompleted += (o, e) => 
{
    f.ProgressAmount = 100;
    f.Close();
}

worker.RunWorkerAsync();

If your method is updating the UI, you'll have to change it to return the results, and then display them in the worker's RunWorkerCompleted event.

You can also use the ProgressChanged event and ReportProgress method to have more granular progress updates.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273784

Your current approach is not well suited for using a Thread (Bgw or otherwise).

The main problem is the 'waiting' part before setting progress=100. What should the this method be doing in that time?

You can reverse the logic, launch a Bgw and use the Progress and Completed events to Update resp. Close your form.

Upvotes: 2

Related Questions