C# - Background Thread

There is a time where you need to implement a task on another thread to prevent freezing your UI, update your UI when the task is done. For that, you can use BackgroundWorker that is provided in the .Net Framework.

BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(BgwDoWork);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgwRunWorkerCompleted);

DoWork event is invoked when this backgroundworker is called while RunWorkerCompleted is invoked when backgroundworker completed the task. All long running and intensive task is implemented in the BgwDoWork function and BgwRunWorkerCompleted function is used to update the main thread or UI. When you wan to start the thread, just called the RunWorkerAsync.

bgw.RunWorkerAsync(); // or
bgw.RunWorkerAsysnc(someobject); //if you need to pass parameter

private void BgwDoWork(object sender, DoWorkEventArgs e)
{
     SomeObject test = e.parameter as SomeObject;
     ......
     // perform some task
     ......
     e.Result = result;
}

private void BgwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     SomeObject2 test2 = e.Result as SomeObject2;
     .....
     // Update main thread or UI
}


e.Result in BgwDoWork is used to pass object between backgroundworker thread to main thread. If you pass a parameter when calling the RunWorkerAsync, you can get this with e.parameter. You can also report the progress of your running task but you need to set WorkerReportsProgress to true when you declare the backgroundworker variable.

bgw.WorkerReportsProgress = true;
bgw.ProgressChanged += new ProgressChangedEventHandler(BgwProgressChanged);

private void BgwDoWork(object sender, DoWorkEventArgs e)
{
     BackgroundWorker bgWorker = (BackgroundWorker)sender;
     ......
     // perform some task
     bgWorker.ReportProgress(someobject);
     ......
}

private void BgwProgressChanged(object sender, ProgressChangedEventArgs e)
{
     // update progress bar or any UI
}

0 comments:

Post a Comment

top