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

Create successful ePaper yourself

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

There are a few things to be wary of when using pooled threads:<br />

• You cannot set the Name of a pooled thread, making debugging<br />

more difficult (although you can attach a description<br />

when debugging in Visual Studio’s Threads window).<br />

• Pooled threads are always background threads (this is usually<br />

not a problem).<br />

• Blocking a pooled thread may trigger additional latency in<br />

the early life of an application unless you call Thread<br />

Pool.SetMinThreads (see the section “Optimizing the<br />

Thread Pool” on page 805).<br />

You are free to change the priority of a pooled thread—it will<br />

be restored to normal when released back to the pool.<br />

You can query if you’re currently executing on a pooled thread via the property<br />

Thread.CurrentThread.IsThreadPoolThread.<br />

Entering the Thread Pool via TPL<br />

You can enter the thread pool easily using the Task classes in the Task Parallel Library.<br />

These were introduced in Framework 4.0: if you’re familiar with the older<br />

constructs, consider the nongeneric Task class a replacement for ThreadPool.QueueU<br />

serWorkItem, and the generic Task a replacement for asynchronous delegates.<br />

The newer constructs are faster, more convenient, and more flexible than the<br />

old.<br />

To use the nongeneric Task class, call Task.Factory.StartNew, passing in a delegate<br />

of the target method:<br />

static void Main() // The Task class is in System.Threading.Tasks<br />

{<br />

Task.Factory.StartNew (Go);<br />

}<br />

static void Go()<br />

{<br />

Console.WriteLine ("Hello from the thread pool!");<br />

}<br />

Task.Factory.StartNew returns a Task object, which you can then use to monitor the<br />

task—for instance, you can wait for it to complete by calling its Wait method.<br />

Any unhandled exceptions are conveniently rethrown onto the<br />

host thread when you call a task’s Wait method. (If you don’t<br />

call Wait and abandon the task, an unhandled exception will<br />

shut down the process, as with an ordinary thread.)<br />

Thread Pooling | 801<br />

Threading

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

Saved successfully!

Ooh no, something went wrong!