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

Create successful ePaper yourself

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

Threads ❘ 847<br />

➤➤<br />

➤➤<br />

Call Task.Run. This is basically a simplified version of Task.Factory.StartNew.<br />

Call the TaskFactory class’s ContinueWhenAll or ContinueWhenAny methods to create<br />

Tasks that start after some or all of a set of previous Tasks completes.<br />

The following code shows one of the simplest cases in which a program starts four Tasks and then<br />

waits for them all to complete.<br />

// Start four tasks.<br />

Task task0 = new Task(FindFibonacci, 0);<br />

task0.Start();<br />

Task task1 = new Task(FindFibonacci, 1);<br />

task1.Start();<br />

Task task2 = new Task(FindFibonacci, 2);<br />

task2.Start();<br />

Task task3 = new Task(FindFibonacci, 3);<br />

task3.Start();<br />

// Wait for the tasks to complete.<br />

task0.Wait();<br />

task1.Wait();<br />

task2.Wait();<br />

task3.Wait();<br />

Threads<br />

The System.Threading.Thread class gives you more control over threads than you can get from<br />

the other techniques described in this appendix, but using it is more complicated. The following<br />

table lists the Thread class’s most useful properties.<br />

Property<br />

IsAlive<br />

IsBackground<br />

Priority<br />

ThreadState<br />

Meaning<br />

Returns true if the thread has been started and has not ended or<br />

aborted.<br />

Determines whether the thread is a background thread.<br />

Determines the thread’s priority. This can be Highest, AboveNormal,<br />

Normal, BelowNormal, or Lowest.<br />

Returns the thread’s state. This can be a combination of the values<br />

Aborted, AbortRequested, Background, Running, Stopped,<br />

StopRequested, Suspended, SuspendRequested, Unstarted, and<br />

WaitSleepJoin.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!