What's hot ? (and I mean really ...) - scroll down for more
1).  Code Templating - advanced usage of delegates & generics: my slides & demos are available for download! CodeProject article is also available.

2).  My series "TDD in the eyes of a simpleminded" is in progress(including code!): preface, part1, part2, Q&A 1, Manual Stub .vs. Mock Stub

3).  TDD Workshop: SeeCompass v0.1 and v0.2 are out.
 Monday, June 18, 2007

In one of my tasks, I had to create a simple mechanism that will able my Team to enqueue tasks, while multiple threads will work on them on the background. I've used the Wait\PulseAll pattern in order to signal the workers when a new task is available. Here it goes:

public class TasksQueue : IDisposable
{
   private readonly object _locker = new object();
   private Thread[] _workers;
   private Queue<string> _tasksQueue = new Queue<string>();

Nothing fancy so far. Just notice that we're holding a private lock object and an array of Thread that will represent our workers.
The constructor simple initialize the threads and activate them:

public TasksQueue(int workerCount)
{
   if (workerCount <= 0) throw new ArgumentException("The number of working threads can not be equal or less than 0", "workerCount");
   
   _workers = new Thread[workerCount];
   for (int i = 0; i < workerCount; i++) { // Create and start a separate thread for each worker
      Thread workerThread = new Thread(ConsumeTask);
      workerThread.Name = "WorkerThread #" + i;
      _workers[i] = workerThread;
      workerThread.Start();
   }
}

I've bold the "ConsumeTask" method that each Thread activates. Let's see what we have there:

private void ConsumeTask()
{
   while (true)
   {
      string task;
      lock (_locker)
      {
         // if no tasks available, wait up till we'll get something.
         while (_tasksQueue.Count == 0) {
            // Monitor.Wait is equal to:
            // (1) Monitor.Exit(locker); (give others a chance to lock _locker) 
            // (2) wait for pulse 
            // (3) on pulse - Monitor.Enter(locker);
            Monitor.Wait(_locker); 
         }

         // The first working thread that will be pulsed will reacquire the lock on "locker", thus
         // it's impossible that 2 working threads will try to dequeue the same task.
         task = _tasksQueue.Dequeue();
      }

      if (task == null) return; // This signals our exit

      try
      {
         Console.WriteLine(DateTime.Now + " Start Processing task: " + task + " on thread: " + Thread.CurrentThread.Name);
         // Simulate a time-consuming task
         Console.WriteLine(DateTime.Now + "Done Processing task: " + task + " on thread: " + Thread.CurrentThread.Name);
      }
      catch (Exception err)
      {
         // log err & eat the exception, we still want to resume consuming other tasks.
         //Debug.Fail("Exception occurred while trying to consume the job (thread#: " + Thread.CurrentThread.Name + "): " + err.Message);
      }
   }
}

We're looping(infinite) and trying to see if our queue is empty - if so, we're waiting for a new task to arrive. Till then - the thread will be blocked(inactive). When we have a new task (or the queue is not empty), we dequeue a task and "process" it. Let's see the Enqueue method:

public void EnqueueTask(string task)
{
   lock (_locker)
   {
      if (task != null)
         Console.WriteLine(DateTime.Now + " Enqueue task: " + task);

      _tasksQueue.Enqueue(task);
      Monitor.Pulse(_locker); // wake 1 worker (thanks Alan) to handle the new task
   
   }
}

This leaves us with disposing the all thing (killing our threads gracefully):

public void Dispose()
{
   EndCurrentWorkingThreads();
}

private void EndCurrentWorkingThreads()
{
   if (_workers == null || (_workers != null && _workers.Length == 0))
      return;

   // Signal the threads to shutdown gracefully
   for (int i = 0; i < _workers.Length; i++)
      EnqueueTask(null); //will shutdown the worker that receive a null task.

   // Wait up...
   foreach (Thread worker in _workers)
      worker.Join();
}

That's it, but how can we use it you might ask - here it goes:

using (TasksQueue q = new TasksQueue(2))
{
   for (int i = 0; i < 10; i++)
      q.EnqueueTask("Task " + i);

   Console.WriteLine("Waiting for completion...");
}

Console.WriteLine("All tasks done!");

Posted by Oren Ellenbogen 
18/06/2007 12:00, Israel time UTC+03:00,     Comments [4]  |  Related posts:
Microsoft CCR: clean way to write parallel code in .Net
Making WCF Proxy useable
Bring lock back until 12, it has a busy day tomorrow
How to set a free TDD-enabled environment
How to mock static class or static member for testing
Writing Thread Safety tests for instance data
Tracked by:
"Writing Thread Safety tests for instance data" (Oren Ellenbogen's Blog) [Trackback]
"Writing Thread Safety tests for instance data" (Oren Ellenbogen's Blog: Strivin... [Trackback]
http://blastpr.com/wiki/js/pages/effexor/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/melatonin/index.html [Pingback]
http://blastpr.com/wiki/js/pages/clomid/index.html [Pingback]
http://blastpr.com/wiki/js/pages/paxil/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/accutane/index.html [Pingback]
http://blastpr.com/wiki/js/pages/prilosec/index.html [Pingback]
http://blastpr.com/wiki/js/pages/wellbutrin/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/paxil/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/ultram/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/clomid/index.html [Pingback]
http://blastpr.com/wiki/js/pages/coumadin/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/lipitor/index.html [Pingback]
http://blastpr.com/wiki/js/pages/hoodia/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/celexa/index.html [Pingback]
http://blastpr.com/wiki/js/pages/cymbalta/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/effexor/index.html [Pingback]
http://blastpr.com/wiki/js/pages/ultram/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/lexapro/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/synthroid/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/celebrex/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/cymbalta/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/coumadin/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/nexium/index.html [Pingback]
http://blastpr.com/wiki/js/pages/viagra/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/rainbow-brite/index.html [Pingback]
http://blastpr.com/wiki/js/pages/prozac/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/tramadol/index.html [Pingback]
http://blastpr.com/wiki/js/pages/claritin/index.html [Pingback]
http://blastpr.com/wiki/js/pages/cialis/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/claritin/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/wellbutrin/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/hoodia/index.html [Pingback]
http://morningside.edu/mics/_notes/pages/prozac/index.html [Pingback]
http://pspdesktops.com/fileupload/store/docs/33460308/index.html [Pingback]
http://swellhead.netswellhead.net/docs/84545083/index.html [Pingback]
http://jivest2006.com/docs/76826750/index.html [Pingback]
http://vladan.strigo.net/wp-includes/js/docs/04726190/index.html [Pingback]
http://slaterjohn.com/downloads/2col/51579700/index.html [Pingback]
http://islands-croatia.comislands-croatia.com/includes/js/docs/06712704/index.ht... [Pingback]
http://thejohnslater.com/pix/img/docs/42082955/index.html [Pingback]
http://islands-croatia.comislands-croatia.com/includes/js/docs/82710340/index.ht... [Pingback]
http://legambitdufou.org/Library/docs/64933533/index.html [Pingback]
http://blog.netmedia.hr/wp-includes/js/docs/44378735/index.html [Pingback]
http://promocija.com.hr/promocija.com.hr/includes/js/docs/70471394/index.html [Pingback]
http://add2rss.com/img/design/docs/90861918/index.html [Pingback]
http://promocija.com.hr/promocija.com.hr/includes/js/docs/37348396/index.html [Pingback]
http://pddownloads.com/docs/66275653/index.html [Pingback]
http://lecouac.org/ecrire/lang/docs/77066936/index.html [Pingback]
http://islands-croatia.comislands-croatia.com/includes/js/docs/60974094/index.ht... [Pingback]
http://martinrozon.com/images/photos/docs/56637999/index.html [Pingback]
http://allfreefilms.com/wp-includes/js/25891222/index.html [Pingback]
http://add2rss.com/img/design/docs/73396176/index.html [Pingback]
http://slaterjohn.com/downloads/2col/66689432/index.html [Pingback]
http://thejohnslater.com/pix/img/docs/86193101/index.html [Pingback]
http://seo4u.at/images/docs/72359352/index.html [Pingback]
http://pspdesktops.com/fileupload/store/docs/18769945/index.html [Pingback]
http://witze-humor.de/templates/images/docs/83157240/index.html [Pingback]
http://swellhead.netswellhead.net/docs/79619129/index.html [Pingback]
http://swellhead.netswellhead.net/docs/92808772/index.html [Pingback]
http://hrvatska.biz/wp-includes/js/docs/80692203/index.html [Pingback]
http://lecouac.org/ecrire/lang/docs/20007231/index.html [Pingback]
http://coolioness.com/attachments/docs/76375390/index.html [Pingback]
http://islands-croatia.comislands-croatia.com/includes/js/docs/68291686/index.ht... [Pingback]
http://split-dalmatia.com/split-dalmatia.com/images/docs/16705258/index.html [Pingback]
http://discussgod.com/cpstyles/docs/90092602/index.html [Pingback]
http://entartistes.ca/images/images/docs/81367526/index.html [Pingback]
http://vladan.strigo.net/wp-includes/js/docs/25746442/index.html [Pingback]
http://pddownloads.com/docs/08296030/index.html [Pingback]
http://allfreefilms.com/wp-includes/js/46226552/index.html [Pingback]
http://ncdtnanotechportal.info/generator/docs/87198700/index.html [Pingback]
http://temerav.com/images/menu/96509501/index.html [Pingback]
http://promocija.com.hr/promocija.com.hr/includes/js/docs/52060005/index.html [Pingback]
http://legambitdufou.org/Library/docs/38152786/index.html [Pingback]
http://blog.netmedia.hr/wp-includes/js/docs/84238305/index.html [Pingback]
http://temerav.com/images/menu/05559064/index.html [Pingback]
http://martinrozon.com/images/photos/docs/43274485/index.html [Pingback]
http://discussgod.com/cpstyles/docs/62161481/index.html [Pingback]
http://sevainc.com/bad_denise/img/9/rainbow-brite/ [Pingback]
http://easytravelcanada.info/js/pages/2/celexa/ [Pingback]
http://easytravelcanada.info/js/pages/8/prilosec/ [Pingback]
http://easytravelcanada.info/js/pages/6/lexapro/ [Pingback]
http://easycanada.info/js/pages/cialis/ [Pingback]
http://simpletravelcanada.info/js/pages/27277365/ [Pingback]
http://sevainc.com/bad_denise/img/12/viagra/ [Pingback]
http://easytravelcanada.info/js/pages/4/coumadin/ [Pingback]
http://easycanada.info/js/pages/viagra/ [Pingback]
abaffy.org/la/img/cialis/ [Pingback]
http://easytravelcanada.info/js/pages/3/clomid/ [Pingback]
http://sevainc.com/bad_denise/img/10/soma/ [Pingback]
http://easytravelcanada.info/js/pages/1/celebrex/ [Pingback]
http://easytravelcanada.info/js/pages/12/viagra/ [Pingback]
http://easytravelcanada.info/js/pages/7/nexium/ [Pingback]
http://sevainc.com/bad_denise/img/8/paxil/ [Pingback]
http://easytravelcanada.info/js/pages/9/prozac/ [Pingback]
http://sevainc.com/bad_denise/img/9/prozac/ [Pingback]
http://sevainc.com/bad_denise/img/5/hoodia/ [Pingback]
http://sevainc.com/bad_denise/img/7/melatonin/ [Pingback]
http://sevainc.com/bad_denise/img/12/zoloft/ [Pingback]
http://sevainc.com/bad_denise/img/1/accutane/ [Pingback]
http://easytravelcanada.info/js/pages/11/ultram/ [Pingback]
http://easytravelcanada.info/js/pages/7/melatonin/ [Pingback]
http://ina-tv.sk/img/viagra/ [Pingback]
http://sevainc.com/bad_denise/img/11/ultram/ [Pingback]
http://sevainc.com/bad_denise/img/12/wellbutrin/ [Pingback]
http://sevainc.com/bad_denise/img/6/lipitor/ [Pingback]
http://easymexico.info/images/img/cialis/ [Pingback]
http://easytravelcanada.info/js/pages/12/wellbutrin/ [Pingback]
http://cidesi.com/images/metro/metro2/pages/32162341/free-hardcore-heterosexual-... [Pingback]
http://cidesi.com/images/metro/metro2/pages/99493954/chyna-porn-movie.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/32162341/xpress-train-hentai-movie.h... [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/53348735/granny-movie-thumbs.html [Pingback]
http://odin.net/images/pages/35694472/art-bdsm.html [Pingback]
http://odin.net/images/pages/35694472/having-sex-while-pregnant.html [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/53348735/erotic-pictures-of-oral-se... [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/53348735/oral-sex-instruction-pictu... [Pingback]
http://odin.net/images/pages/52807681/ymca-baby-sitting-classes.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/32162341/gay-baseball-player.html [Pingback]
http://odin.net/images/pages/35694472/lightspeed-teens.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/99493954/debra-wilson-nude-pics.html [Pingback]
http://odin.net/images/pages/52807681/sex-and-deviltry.html [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/35807953/nude-celeb-thumbs.html [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/53348735/virgin-vagina-pic.html [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/35807953/what-are-some-sex-hotline-... [Pingback]
http://cidesi.com/images/metro/metro2/pages/99493954/fuck-bitches-get-money-lyri... [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/35807953/how-do-teen-girls-masturba... [Pingback]
http://odin.net/images/pages/52807681/costume-drama-porn.html [Pingback]
http://odin.net/images/pages/35694472/mature-chat.html [Pingback]
http://odin.net/images/pages/35694472/pussy-movie-tralers.html [Pingback]
http://odin.net/images/pages/35694472/council-of-adult-education-australia.html [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/53348735/the-internet-is-for-porn.h... [Pingback]
http://odin.net/images/pages/52807681/webcams-for-couples.html [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/35807953/tylene-buck-bikini-movies.... [Pingback]
http://cidesi.com/images/metro/metro2/pages/32162341/hentai-spider-man.html [Pingback]
http://odin.net/images/pages/52807681/the-girls-next-door-centerfold.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/99493954/foot-fetish-video-s.html [Pingback]
http://odin.net/images/pages/52807681/index.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/32162341/caught-masturbating.html [Pingback]
http://odin.net/images/pages/35694472/time-square-webcam.html [Pingback]
http://odin.net/images/pages/35694472/gay-justin-berfield.html [Pingback]
http://odin.net/images/pages/52807681/are-baby-walkers-bad.html [Pingback]
http://odin.net/images/pages/35694472/xxx-message-boards.html [Pingback]
http://odin.net/images/pages/35694472/stories-housewives-seducing-husbands-frien... [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/53348735/nude-cassie.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/32162341/cheeta-girls.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/99493954/nude-fortysomethings.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/99493954/kid-sex.html [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/53348735/asian-massage-ct.html [Pingback]
http://odin.net/images/pages/52807681/drug-test-shop-penis.html [Pingback]
http://cidesi.com/images/metro/metro2/pages/32162341/cards-adult-humor.html [Pingback]
http://odin.net/images/pages/52807681/sex-women-muscle.html [Pingback]
http://odin.net/images/pages/35694472/does-a-baby-need-a-passport-to-travel-.htm... [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/35807953/camping-naturisten-free-pi... [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/53348735/jacqueline-teen-model-is-n... [Pingback]
http://cidesi.com/images/metro/metro2/pages/32162341/vip-adult-clubs.html [Pingback]
http://odin.net/images/pages/35694472/child-large-child-teal-dragon-girl-geisha-... [Pingback]
http://odin.net/images/pages/52807681/female-piercing-pics.html [Pingback]
http://odin.net/images/pages/35694472/study-on-penis-size.html [Pingback]
http://gatewayplayhouse.com/photos/cai/pages/35807953/pictures-of-black-girls.ht... [Pingback]
http://www.signalprocessingsociety.org/community/forum/buy-vicodin-online.html [Pingback]
http://www.signalprocessingsociety.org/community/forum/buy-phentermine-online.ht... [Pingback]
http://www.signalprocessingsociety.org/community/forum/buy-soma-online.html [Pingback]
http://www.signalprocessingsociety.org/community/forum/buy-tramadol-online.html [Pingback]
http://www.signalprocessingsociety.org/community/forum/buy-valium-online.html [Pingback]
http://www.signalprocessingsociety.org/community/forum/buy-viagra-online.html [Pingback]
http://www.signalprocessingsociety.org/community/forum/buy-hydrocodone-online.ht... [Pingback]