12.07.2015 Views

Accelerated

Accelerated

Accelerated

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 12 ■ THREADING IN C# 333}private static void RndThreadFunc() {// Manage thread count and wait for a// random amount of time between 1 and 12// seconds.Interlocked.Increment( ref numberThreads );try {int time = rnd.Next( 1000, 12000 );Thread.Sleep( time );}finally {Interlocked.Decrement( ref numberThreads );}}private static void RptThreadFunc() {while( true ) {int threadCount = 0;threadCount =Interlocked.Exchange( ref numberThreads,numberThreads );Console.WriteLine( "{0} thread(s) alive",threadCount );Thread.Sleep( 1000 );}}static void Main() {// Start the reporting threads.Thread reporter =new Thread( new ThreadStart(EntryPoint.RptThreadFunc) );reporter.IsBackground = true;reporter.Start();}// Start the threads that wait random time.Thread[] rndthreads = new Thread[ 50 ];for( uint i = 0; i < 50; ++i ) {rndthreads[i] =new Thread( new ThreadStart(EntryPoint.RndThreadFunc) );rndthreads[i].Start();}This little program creates 50 foreground threads that do nothing but wait a random period oftime between 1 and 12 seconds. It also creates a background thread that reports how many threadsare currently alive. If you look at the RndThreadFunc method, which is the thread function that the 50threads use, you can see it increment and decrement the integer value using the Interlocked methods.Notice that I use a finally block to ensure that the value gets decremented no matter how thethread exits. You could use the disposable trick with the using keyword by wrapping the incrementand decrement in a separate class that implements IDisposable. That would get rid of the uglyfinally block. But, in this case, it wouldn’t help you at all, since you’d also have to create a referencetype to contain the integer count variable, as you cannot store a ref to the integer as a field in thehelper class.

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

Saved successfully!

Ooh no, something went wrong!