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.

TaskCreationOptions atp = TaskCreationOptions.AttachedToParent;<br />

var parent = Task.Factory.StartNew (() =><br />

{<br />

Task.Factory.StartNew (() => // Child<br />

{<br />

Task.Factory.StartNew (() => { throw null; }, atp); // Grandchild<br />

}, atp);<br />

});<br />

// The following call throws a NullReferenceException (wrapped<br />

// in nested AggregateExceptions):<br />

parent.Wait();<br />

Interestingly, if you check a task’s Exception property after it<br />

has thrown an exception, the act of reading that property will<br />

prevent the exception from subsequently taking down your application.<br />

The rationale is that PFX’s designers don’t want you<br />

ignoring exceptions—as long as you acknowledge them in some<br />

way, they won’t punish you by terminating your program.<br />

An unhandled exception on a task doesn’t cause immediate application<br />

termination: instead, it’s delayed until the garbage<br />

collector catches up with the task and calls its finalizer. Termination<br />

is delayed because it can’t be known for certain that you<br />

don’t plan to call Wait or check its Result or Exception property<br />

until the task is garbage-collected. This delay can sometimes<br />

mislead you as to the original source of the error (although Visual<br />

Studio’s debugger can assist if you enable breaking on firstchance<br />

exceptions).<br />

As we’ll see soon, an alternative strategy for dealing with exceptions is with<br />

continuations.<br />

Canceling Tasks<br />

You can optionally pass in a cancellation token when starting a task. This lets you<br />

cancel tasks via the cooperative cancellation pattern described in “Safe Cancellation”<br />

on page 857 in Chapter 21:<br />

var cancelSource = new CancellationTokenSource();<br />

CancellationToken token = cancelSource.Token;<br />

Task task = Task.Factory.StartNew (() =><br />

{<br />

// Do some stuff...<br />

token.ThrowIfCancellationRequested(); // Check for cancellation request<br />

// Do some stuff...<br />

}, token);<br />

...<br />

cancelSource.Cancel();<br />

Task Parallelism | 903<br />

Parallel<br />

Programming

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

Saved successfully!

Ooh no, something went wrong!