15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

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

using System;<br />

using System.Threading;<br />

namespace Wrox.ProCSharp.Threading<br />

{<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

int nWorkerThreads;<br />

int nCompletionPortThreads;<br />

ThreadPool.GetMaxThreads(out nWorkerThreads, out nCompletionPortThreads);<br />

Console.WriteLine("Max worker threads: {0}, " +<br />

"I/O completion threads: {1}",<br />

nWorkerThreads, nCompletionPortThreads);<br />

}<br />

for (int i = 0; i < 5; i++)<br />

{<br />

ThreadPool.QueueUserWorkItem(JobForAThread);<br />

}<br />

Thread.Sleep(3000);<br />

}<br />

}<br />

static void JobForAThread(object state)<br />

{<br />

for (int i = 0; i < 3; i++)<br />

{<br />

Console.WriteLine("loop {0}, running inside pooled thread {1}",<br />

i, Thread.CurrentThread.ManagedThreadId);<br />

Thread.Sleep(50);<br />

}<br />

}<br />

code snippet ThreadPoolSamples/Program.cs<br />

When you run the application, you can see that 50 worker threads are possible with the current settings.<br />

The five jobs are processed by just two pooled threads. Your experience may be different, <strong>and</strong> you can also<br />

change the sleep time with the job <strong>and</strong> the number of jobs to process to get very different results.<br />

Max worker threads: 1023, I/O completion threads: 1000<br />

loop 0, running inside pooled thread 4<br />

loop 0, running inside pooled thread 3<br />

loop 1, running inside pooled thread 4<br />

loop 1, running inside pooled thread 3<br />

loop 2, running inside pooled thread 4<br />

loop 2, running inside pooled thread 3<br />

loop 0, running inside pooled thread 4<br />

loop 0, running inside pooled thread 3<br />

loop 1, running inside pooled thread 4<br />

loop 1, running inside pooled thread 3<br />

loop 2, running inside pooled thread 4<br />

loop 2, running inside pooled thread 3<br />

loop 0, running inside pooled thread 4<br />

loop 1, running inside pooled thread 4<br />

loop 2, running inside pooled thread 4<br />

Thread pools are very easy to use. However, there are some restrictions:<br />

➤<br />

➤<br />

All thread pool threads are background threads. If all foreground threads of a process are finished, all<br />

background threads are stopped. You cannot change a pooled thread to a foreground thread.<br />

You cannot set the priority or name of a pooled thread.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!