BackgroundWorker
suggest changeSee below for a simple example of how to use a BackgroundWorker
object to perform time-intensive operations in a background thread.
You need to:
- Define a worker method that does the time-intensive work and call it from an event handler for the
DoWork
event of aBackgroundWorker
. - Start the execution with
RunWorkerAsync
. Any argument required by the worker method attached toDoWork
can be passed in via theDoWorkEventArgs
parameter toRunWorkerAsync
.
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.
- The
RunWorkerCompleted
event is triggered when theDoWork
handlers have completed. - The
ProgressChanged
event is triggered when theReportProgress
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);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents