15.02.2015 Views

C# 4 and .NET 4

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

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

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

t1.Wait();<br />

}<br />

catch (Exception ex)<br />

{<br />

Console.WriteLine("exception: {0}, {1}", ex.GetType().Name,<br />

ex.Message);<br />

if (ex.InnerException != null)<br />

Console.WriteLine("inner exception: {0}, {1}",<br />

ex.InnerException.GetType().Name,<br />

ex.InnerException.Message);<br />

}<br />

Console.WriteLine("status of the task: {0}", t1.Status);<br />

code snippet CancellationSamples/Program.cs<br />

When running the application, you can see that the task starts, runs for a few loops, <strong>and</strong> gets the<br />

cancellation request. The task is canceled <strong>and</strong> throws a TaskCanceledException, which is initiated<br />

from the method call ThrowIfCancellationRequested(). With the caller waiting for the task,<br />

you can see that the exception AggregateException is caught <strong>and</strong> contains the inner exception<br />

TaskCanceledException. This is used for a hierarchy of cancellations, for example, if you run a<br />

Parallel.For within a task that is canceled as well. The final status of the task is Canceled.<br />

in task<br />

in loop<br />

in loop<br />

in loop<br />

in loop<br />

*** task canceled<br />

canceling was requested, canceling from within the task<br />

exception AggregateException, One or more errors occurred.<br />

inner exception TaskCanceledException, A task was canceled.<br />

status of the task: Canceled<br />

Threading issues<br />

Programming with multiple threads is not easy. When starting multiple threads that access the same data,<br />

you can get intermittent problems that are hard to find. This is the same if you use tasks, Parallel LINQ,<br />

or the Parallel class. To avoid getting into trouble, you must pay attention to synchronization issues <strong>and</strong><br />

the problems that can happen with multiple threads. We discuss two in particular next: race conditions<br />

<strong>and</strong> deadlocks.<br />

race Condition<br />

A race condition can occur if two or more threads access the same objects <strong>and</strong> access to the shared state is<br />

not synchronized.<br />

To demonstrate a race condition, the class StateObject, with an int field <strong>and</strong> the method ChangeState, is<br />

defined. In the implementation of ChangeState, the state variable is verified to see if it contains 5; if it does,<br />

the value is incremented. Trace.Assert is the next statement, which immediately verifies that state now<br />

contains the value 6.<br />

After incrementing by 1 a variable that contains the value 5, you might expect that the variable now has the<br />

value 6. But this is not necessarily the case. For example, if one thread has just completed the if (state == 5)<br />

statement, it might be preempted <strong>and</strong> the scheduler run another thread. The second thread now goes into the if<br />

body <strong>and</strong>, because the state still has the value 5, the state is incremented by 1 to 6. The first thread is now<br />

scheduled again, <strong>and</strong> in the next statement the state is incremented to 7. This is when the race condition<br />

occurs <strong>and</strong> the assert message is shown.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!