See below for a simple example of how to use a BackgroundWorker
object to perform time-intensive operations in a background thread.
You need to:
DoWork
event of a BackgroundWorker
.RunWorkerAsync
. Any argument required by the worker method attached to DoWork
can be passed in via the DoWorkEventArgs
parameter to RunWorkerAsync
.In addition to the DoWork
event the BackgroundWorker
class also defines two events that should be used for interacting with the user interface. These are optional.
RunWorkerCompleted
event is triggered when the DoWork
handlers have completed.ProgressChanged
event is triggered when the ReportProgress
method is called.public void ProcessDataAsync()
{
// Start the time intensive method
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += BwDoWork;
bw.RunWorkerCompleted += BwRunWorkerCompleted;
bw.RunWorkerAsync(@"PATH_TO_SOME_FILE");
// Control returns here before TimeintensiveMethod returns
Console.WriteLine("You can read this while TimeintensiveMethod is still running.");
}
// Method that will be called after BwDoWork exits
private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// we can access possible return values of our Method via the Parameter e
Console.WriteLine("Count: " + e.Result);
}
// execution of our time intensive Method
private void BwDoWork(object sender, DoWorkEventArgs e)
{
e.Result = TimeintensiveMethod(e.Argument);
}
private int TimeintensiveMethod(object file)
{
Console.WriteLine("Start TimeintensiveMethod.");
// Do some time intensive calculations...
using (StreamReader reader = new StreamReader(file.ToString()))
{
string s = reader.ReadToEnd();
for (int i = 0; i < 10000; i++)
s.GetHashCode();
}
Console.WriteLine("End TimeintensiveMethod.");
// return something as a "result"
return new Random().Next(100);
}