03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

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.

Tasks ❘ 845<br />

Parallel.For<br />

The Parallel.For method takes as parameters a starting value, an ending value, and a delegate. It<br />

invokes the delegate for each of the values between the starting value (including that value) and the<br />

ending value (not including that value). The method blocks until all the calls to the delegate have<br />

completed and then the code continues.<br />

The following code shows how a program might invoke the FindFibonacci method with the<br />

parameters 0, 1, 2, and 3.<br />

Parallel.For(0, 4, FindFibonacci);<br />

Parallel.ForEach<br />

The Parallel.ForEach method takes as parameters an enumerable collection of values and a delegate.<br />

The ForEach method invokes the delegate, passing it each of the parameter values. The method blocks<br />

until all the calls to the delegate have completed.<br />

The following code shows how a program might call the FindFibonacci method, passing it the<br />

input parameters 0, 2, 4, 6, and 8.<br />

int[] numbers = {0, 2, 4, 6, 8};<br />

Parallel.ForEach(numbers, FindFibonacci);<br />

Parallel.Invoke<br />

The Parallel.Invoke method lets you invoke one or more possibly different delegates. It executes<br />

the delegates, possibly on different threads, and blocks until they all complete.<br />

The following code shows how a program might use Parallel.Invoke to execute the<br />

ResetParameters, LoadGame, and BuildWorld methods in parallel.<br />

Parallel.Invoke(ResetParameters, LoadGame, BuildWorld);<br />

Tasks<br />

The System.Threading.Tasks.Task class enables you to create threads and run them asynchronously.<br />

The following table summarizes the Task class’s most useful properties.<br />

Property<br />

Exception<br />

Factory<br />

IsCanceled<br />

Purpose<br />

Returns an AggregateException object containing information about<br />

any exceptions that caused the Task to end early.<br />

Provides access to TaskFactory class methods that you can use to create<br />

Tasks. (This is explained in more detail shortly.)<br />

Returns true if the Task was canceled.<br />

continues<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!