15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

class Program<br />

{<br />

static BackgroundWorker _bw = new BackgroundWorker();<br />

static void Main()<br />

{<br />

_bw.DoWork += bw_DoWork;<br />

_bw.RunWorkerAsync ("Message to worker");<br />

Console.ReadLine();<br />

}<br />

static void bw_DoWork (object sender, DoWorkEventArgs e)<br />

{<br />

// This is called on the worker thread<br />

Console.WriteLine (e.Argument); // writes "Message to worker"<br />

// Perform time-consuming task...<br />

}<br />

}<br />

BackgroundWorker has a RunWorkerCompleted event that fires after the DoWork event<br />

handler has done its job. Handling RunWorkerCompleted is not mandatory, but you<br />

usually do so in order to query any exception that was thrown in DoWork. Further,<br />

code within a RunWorkerCompleted event handler is able to update user interface<br />

controls without explicit marshaling; code within the DoWork event handler cannot.<br />

To add support for progress reporting:<br />

1. Set the WorkerReportsProgress property to true.<br />

2. Periodically call ReportProgress from within the DoWork event handler with a<br />

“percentage complete” value, and optionally, a user-state object.<br />

3. Handle the ProgressChanged event, querying its event argument’s ProgressPer<br />

centage property.<br />

4. Code in the ProgressChanged event handler is free to interact with UI controls<br />

just as with RunWorkerCompleted. This is typically where you will update a progress<br />

bar.<br />

To add support for cancellation:<br />

1. Set the WorkerSupportsCancellation property to true.<br />

2. Periodically check the CancellationPending property from within the DoWork<br />

event handler. If it’s true, set the event argument’s Cancel property to true, and<br />

return. (The worker can also set Cancel and exit without CancellationPending<br />

being true if it decides that the job is too difficult and it can’t go on.)<br />

3. Call CancelAsync to request cancellation.<br />

Here’s an example that implements all the preceding features:<br />

using System;<br />

using System.Threading;<br />

using System.ComponentModel;<br />

BackgroundWorker | 853<br />

Threading

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

Saved successfully!

Ooh no, something went wrong!