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, however, some cases where you don’t need to handle exceptions on a<br />

worker thread, because the .NET Framework does it for you. These are covered in<br />

upcoming sections, and are:<br />

• Asynchronous delegates<br />

• BackgroundWorker<br />

• The Task Parallel Library (conditions apply)<br />

Thread Pooling<br />

Whenever you start a thread, a few hundred microseconds are spent organizing such<br />

things as a fresh private local variable stack. Each thread also consumes (by default)<br />

around 1 MB of memory. The thread pool cuts these overheads by sharing and recycling<br />

threads, allowing multithreading to be applied at a very granular level without<br />

a performance penalty. This is useful when leveraging multicore processors to<br />

execute computationally intensive code in parallel in “divide-and-conquer” style.<br />

The thread pool also keeps a lid on the total number of worker threads it will run<br />

simultaneously. Too many active threads throttle the operating system with administrative<br />

burden and render CPU caches ineffective. Once a limit is reached, jobs<br />

queue up and start only when another finishes. This makes arbitrarily concurrent<br />

applications possible, such as a web server. (The asynchronous method pattern takes<br />

this further by making highly efficient use of the pooled threads; see Chapter 23.)<br />

There are a number of ways to enter the thread pool:<br />

• Via the Task Parallel Library or PLINQ (from Framework 4.0)<br />

• By calling ThreadPool.QueueUserWorkItem<br />

• Via asynchronous delegates<br />

• Via BackgroundWorker<br />

The following constructs use the thread pool indirectly:<br />

• WCF, Remoting, ASP.NET, and ASMX Web Services application<br />

servers<br />

• System.Timers.Timer and System.Threading.Timer<br />

• Framework methods that end in Async, such as those on<br />

WebClient (the event-based asynchronous pattern), and<br />

most BeginXXX methods (the asynchronous programming<br />

model pattern)<br />

The Task Parallel Library (TPL) and PLINQ are sufficiently powerful and high-level<br />

that you’ll want to use them to assist in multithreading even when thread pooling<br />

is unimportant. We discuss this fully in the following chapter. Right now, we’ll look<br />

briefly at how you can use the Task class as a simple means of running a delegate on<br />

a pooled thread.<br />

800 | Chapter 21: Threading

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

Saved successfully!

Ooh no, something went wrong!