Game Development Reference
In-Depth Information
Executing the Worker Thread
BackgroundWorker executes the DoWork event in a separate thread so the user inter-
face remains responsive. Executing the worker thread is very easy; it's done by invok-
ing the RunWorkerAsync method on the BackgroundWorker . This method optionally
allows you to pass in an argument that the worker logic can use during processing.
The following code shows the implementation details behind the demo that is
available on the Companion Web site for this topic.
private void ComputeButton_Click(object sender, EventArgs e)
{
ResultLabel.Text = string.Empty;
ComputeNumberField.Enabled = false;
ComputeButton.Enabled = false;
CancellationButton.Enabled = true;
int computeNumber = (int)ComputeNumberField.Value;
percentageReached = 0;
backgroundWorker.RunWorkerAsync(computeNumber);
}
No matter how the DoWork event completes, whether successfully or in an erro-
neous manner, the RunWorkerCompleted event will always fire, providing an instance
of RunWorkerCompletedEventArgs that contains the status and result of the operation.
This event will allow you to respond appropriately to whatever result is returned
by the worker thread. When an error occurs, you can retrieve the exception object
from the Error property. This property will be null if no errors occurred during
processing. When a cancellation occurs at the request of the user, the Cancellation
property will be set to true. Otherwise, you can retrieve the result from the Result
property if there is one. The following code shows the completed event handler
that is fired when the processing task is finished.
private void backgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
ResultLabel.Text = String.Format(“Error: {0}”, e.Error.Message);
}
else if (e.Cancelled)
{
Search Nedrilad ::




Custom Search