mardi 28 septembre 2010

Threading en C# - exemple ThreadPool.QueueUserWorkItem

Comme précisé dans l'article "Theading en C# - synchronisation et méthodes de threading", voici un exemple d'utilisation du QueueUserWorkItem (sur le ThreadPool).
Note: les exemples sont développés avec Snippet Compiler.

Ce premier exemple empile 100 workers sur le ThreadPool et attend la fin de l'exécution de tous les worker thread.
Join Pattern pour QueueUserWorkItem
Pour attendre la fin de l'exécution des WorkItems, le programme implémente le Join Pattern à l'aide d'une structure Wait & Pulse et d'un compteur (de 100 à 0, décrémenté comme avec les sémaphores).
Attention que dans un système Wait & Pulse, le Wait doit absolument arrivé avant le premier Pulse (ce qui sera le cas de cet exemple).
Fichier: Threading_ThreadPool_QueueUserWorkItem.
using System;
using System.Collections.Generic;
using System.Threading;

public class MyClass
{
 static object workerLocker = new object();
 static int runningWorkers = 100;
  
 public static void RunSnippet()
 {
  for( int i = 0; i < runningWorkers; i++ )
   ThreadPool.QueueUserWorkItem( DoWork, i );
  WL( "Wait for threads to complete" );
  lock( workerLocker ){
   while( runningWorkers > 0 )
    Monitor.Wait( workerLocker );
  }
 }
 
 public static void DoWork( object instanceData ){
  WL( "Started: "+instanceData );
  
  // Exception Handling must be managed in the Worker method.
  //if( (int)instanceData == 10 )
  // throw new Exception("SBlaff");
  
  Thread.Sleep( 1000 );
  WL( "Ended: "+instanceData );
  lock(workerLocker) {
   runningWorkers--;
   Monitor.Pulse( workerLocker );
  }
 }
 
}

Aucun commentaire: