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.

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

oVerVieW<br />

A thread is an independent stream of instructions in a program. All your <strong>C#</strong> programs up to this point have<br />

one entry point — the Main() method. Execution starts with the fi rst statement in the Main() method <strong>and</strong><br />

continues until that method returns.<br />

This program structure is all very well for programs in which there is one identifi able sequence of tasks,<br />

but often a program needs to do more than one thing at the same time. Threads are important both for<br />

client - side <strong>and</strong> for server - side applications. While you type <strong>C#</strong> code in the Visual Studio editor, the code is<br />

analyzed to underline missing semicolons or other syntax errors. This is done by a background thread. The<br />

same thing is done by the spell checker in Microsoft Word. One thread is waiting for input from the user,<br />

while the other does some background research. A third thread can store the written data in an interim<br />

fi le , wh i le a not her one dow n load s s om e add it ion a l d at a f rom t he I nt er ne t .<br />

In an application that is running on the server, one thread, the listener thread, waits for a request from<br />

a client. As soon as the request comes in, the request is forwarded to a separate worker thread, which<br />

continues the communication with the client. The listener thread immediately comes back to get the next<br />

request from the next client.<br />

A process contains resources, such as Window h<strong>and</strong>les, h<strong>and</strong>les to the fi le system, or other kernel objects.<br />

Every process has virtual memory allocated. A process contains at least one thread. The operating system<br />

schedules threads. A thread has a priority, a program counter for the program location where it is actually<br />

processing, <strong>and</strong> a stack in which to store its local variables. Every thread has its own stack, but the memory for<br />

the program code <strong>and</strong> the heap are shared among all threads of a single process. This makes communication<br />

among threads of one process fast — the same virtual memory is addressed by all threads of a process.<br />

However, this also makes things diffi cult because multiple threads can change the same memory location.<br />

A process manages resources, which include virtual memory <strong>and</strong> Window h<strong>and</strong>les, <strong>and</strong> contains at least one<br />

thread. A thread is required to run the program.<br />

asynChronous delegaTes<br />

A simple way to create a thread is by defi ning a delegate <strong>and</strong> invoking the delegate asynchronously. In<br />

Chapter 8, “ Delegates, Lambdas, <strong>and</strong> Events, ” you saw delegates as type - safe references to methods. The<br />

Delegate class also supports invoking the methods asynchronously. Behind the scenes, the Delegate class<br />

creates a thread that fulfi lls the task.<br />

The delegate uses a thread pool for asynchronous tasks. Thread pools are discussed<br />

later in this chapter.<br />

To demonstrate the asynchronous features of delegates, start with a method that takes a while to complete.<br />

The method TakesAWhile() needs at least the number of milliseconds passed with the second argument to<br />

fi n i sh b e c au s e of t he Thread.Sleep() method:<br />

static int TakesAWhile(int data, int ms)<br />

{<br />

Console.WriteLine("TakesAWhile started");<br />

Thread.Sleep(ms);<br />

Console.WriteLine("TakesAWhile completed");<br />

return ++data;<br />

}<br />

code snippet AsyncDelegate/Program.cs<br />

To invoke this method from a delegate, a delegate with the same parameter <strong>and</strong> return types must be<br />

defi ned, as shown by the delegate TakesAWhileDelegate :<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!