15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

538 ❘ ChaPTer 20 threAds, tAsks, And synchrOnizAtiOn<br />

The completion h<strong>and</strong>ler OnWorkCompleted() is invoked if the asynchronous method has completed<br />

successfully or if it was canceled. If it was canceled, you cannot access the Result property, because this<br />

throws an InvalidOperationException with the information that the operation has been canceled. So,<br />

you have to check the Cancelled property of RunWorkerCompletedEventArgs <strong>and</strong> behave accordingly.<br />

private void OnWorkCompleted(object sender,<br />

RunWorkerCompletedEventArgs e)<br />

{<br />

if (e.Cancelled)<br />

{<br />

this.textResult.Text = "Cancelled";<br />

}<br />

else<br />

{<br />

this.textResult.Text = e.Result.ToString();<br />

}<br />

this.buttonCalculate.IsEnabled = true;<br />

this.buttonCancel.IsEnabled = false;<br />

}<br />

Running the application once more, you can cancel the asynchronous progress from the user interface.<br />

enable Progress<br />

To get progress information to the user interface, you must set the BackgroundWorker property<br />

WorkerReportsProgress to true.<br />

With the OnDoWork method, you can report the progress to the BackgroundWorker control with the<br />

ReportProgress() method:<br />

private void OnDoWork(object sender, DoWorkEventArgs e)<br />

{<br />

var t = e.Argument as Tuple;<br />

for (int i = 0; i < 10; i++)<br />

{<br />

Thread.Sleep(500);<br />

backgroundWorker.ReportProgress(i * 10);<br />

if (backgroundWorker.CancellationPending)<br />

{<br />

e.Cancel = true;<br />

return;<br />

}<br />

}<br />

}<br />

e.Result = t.Item1 + t.Item2;<br />

code snippet BackgroundWorkersSample/Window1.xaml.cs<br />

The method ReportProgress() fires the ProgressChanged event of the BackgroundWorker control. This<br />

event changes the control to the UI thread.<br />

Add the method OnProgressChanged() to the ProgressChanged event, <strong>and</strong> in the implementation<br />

set a new value to the progress bar control that is received from the property ProgressPercentage of<br />

ProgressChangedEventArgs:<br />

private void OnProgressChanged(object sender, ProgressChangedEventArgs e)<br />

{<br />

this.progressBar.Value = e.ProgressPercentage;<br />

}<br />

In the OnWorkCompleted() event h<strong>and</strong>ler, the progress bar finally is set to the 100% value:<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!