AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > .NET技术

C# 程序员参考--线程处理教程

51自学网 http://www.wanshiok.com
 

示例 3:使用线程池

以下示例显示如何使用线程池。首先创建 ManualResetEvent 对象,此对象使程序能够知道线程池何时运行完所有的工作项。接着,尝试向线程池添加一个线程。如果添加成功,则添加其余的线程(本例中为 4 个)。然后线程池将工作项放入可用线程中。调用 eventX 上的 WaitOne 方法,这会使程序的其余部分等待,直到用 eventX.Set 方法触发事件为止。最后,程序打印出线程上的负载(实际执行某一特定工作项的线程)。

// SimplePool.cs// Simple thread pool exampleusing System;using System.Collections;using System.Threading;// Useful way to store info that can be passed as a state on a work itempublic class SomeState{   public int Cookie;   public SomeState(int iCookie)   {      Cookie = iCookie;   }}public class Alpha{   public Hashtable HashCount;   public ManualResetEvent eventX;   public static int iCount = 0;   public static int iMaxCount = 0;   public Alpha(int MaxCount)    {      HashCount = new Hashtable(MaxCount);      iMaxCount = MaxCount;   }   // Beta is the method that will be called when the work item is   // serviced on the thread pool.   // That means this method will be called when the thread pool has   // an available thread for the work item.   public void Beta(Object state)   {      // Write out the hashcode and cookie for the current thread      Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(),         ((SomeState)state).Cookie);      // The lock keyword allows thread-safe modification      // of variables accessible across multiple threads.      Console.WriteLine(         "HashCount.Count=={0}, Thread.CurrentThread.GetHashCode()=={1}",         HashCount.Count,          Thread.CurrentThread.GetHashCode());      lock (HashCount)       {         if (!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode()))            HashCount.Add (Thread.CurrentThread.GetHashCode(), 0);         HashCount[Thread.CurrentThread.GetHashCode()] =             ((int)HashCount[Thread.CurrentThread.GetHashCode()])+1;      }      // Do some busy work.      // Note: Depending on the speed of your machine, if you       // increase this number, the dispersement of the thread      // loads should be wider.      int iX  = 2000;      Thread.Sleep(iX);      // The Interlocked.Increment method allows thread-safe modification      // of variables accessible across multiple threads.      Interlocked.Increment(ref iCount);      if (iCount == iMaxCount)      {         Console.WriteLine();         Console.WriteLine("Setting eventX ");         eventX.Set();      }   }}public class SimplePool{   public static int Main(string[] args)   {      Console.WriteLine("Thread Pool Sample:");      bool W2K = false;      int MaxCount = 10;  // Allow a total of 10 threads in the pool      // Mark the event as unsignaled.      ManualResetEvent eventX = new ManualResetEvent(false);      Console.WriteLine("Queuing {0} items to Thread Pool", MaxCount);      Alpha oAlpha = new Alpha(MaxCount);  // Create the work items.      // Make sure the work items have a reference to the signaling event.      oAlpha.eventX = eventX;      Console.WriteLine("Queue to Thread Pool 0");      try      {         // Queue the work items, which has the added effect of checking         // which OS is running.         ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),            new SomeState(0));         W2K = true;      }      catch (NotSupportedException)      {         Console.WriteLine("These API's may fail when called on a non-Windows 2000 system.");         W2K = false;      }      if (W2K)  // If running on an OS which supports the ThreadPool methods.      {         for (int iItem=1;iItem < MaxCount;iItem++)         {            // Queue the work items:            Console.WriteLine("Queue to Thread Pool {0}", iItem);            ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),new SomeState(iItem));         }         Console.WriteLine("Waiting for Thread Pool to drain");         // The call to exventX.WaitOne sets the event to wait until         // eventX.Set() occurs.         // (See oAlpha.Beta).         // Wait until event is fired, meaning eventX.Set() was called:         eventX.WaitOne(Timeout.Infinite,true);         // The WaitOne won't return until the event has been signaled.         Console.WriteLine("Thread Pool has been drained (Event fired)");         Console.WriteLine();         Console.WriteLine("Load across threads");         foreach(object o in oAlpha.HashCount.Keys)            Console.WriteLine("{0} {1}", o, oAlpha.HashCount[o]);      }      return 0;   }}

输出示例

注意   下列输出随计算机的不同而不同。
Thread Pool Sample:Queuing 10 items to Thread PoolQueue to Thread Pool 0Queue to Thread Pool 1......Queue to Thread Pool 9Waiting for Thread Pool to drain 98 0 :HashCount.Count==0, Thread.CurrentThread.GetHashCode()==98 100 1 :HashCount.Count==1, Thread.CurrentThread.GetHashCode()==100 98 2 :......Setting eventXThread Pool has been drained (Event fired)Load across threads101 2100 398 4102 1

示例 4:使用 Mutex 对象

可以使用 mutex 对象保护共享资源不被多个线程或进程同时访问。mutex 对象的状态或者设置为终止(当它不属于任何线程时),或者设置为非终止(当它属于某个线程时)。同时只能有一个线程拥有一个 mutex 对象。例如,为了防止两个线程同时写入共享内存,每个线程在执行访问该共享内存的代码之前等待 mutex 对象的所属权。写入共享内存后,线程将释放该 mutex 对象。

此示例阐释如何在处理线程过程中使用 Mutex 类、AutoResetEvent 类和 WaitHandle 类。它还阐释在处理 mutex 对象过程中所用的方法。

// Mutex.cs// Mutex object exampleusing System;using System.Threading;public class MutexSample{   static Mutex gM1;   static Mutex gM2;   const int ITERS = 100;   static AutoResetEvent Event1 = new AutoResetEvent(false);   static AutoResetEvent Event2 = new AutoResetEvent(false);   static AutoResetEvent Event3 = new AutoResetEvent(false);   static AutoResetEvent Event4 = new AutoResetEvent(false);      public static void Main(String[] args)   {      Console.WriteLine("Mutex Sample ...");      // Create Mutex initialOwned, with name of "MyMutex".      gM1 = new Mutex(true,"MyMutex");      // Create Mutex initialOwned, with no name.      gM2 = new Mutex(true);      Console.WriteLine(" - Main Owns gM1 and gM2");      AutoResetEvent[] evs = new AutoResetEvent[4];      evs[0] = Event1;    // Event for t1      evs[1] = Event2;    // Event for t2      evs[2] = Event3;    // Event for t3      evs[3] = Event4;    // Event for t4      MutexSample tm = new MutexSample( );      Thread t1 = new Thread(new ThreadStart(tm.t1Start));      Thread t2 = new Thread(new ThreadStart(tm.t2Start));      Thread t3 = new Thread(new ThreadStart(tm.t3Start));      Thread t4 = new Thread(new ThreadStart(tm.t4Start));      t1.Start( );   // Does Mutex.WaitAll(Mutex[] of gM1 and gM2)      t2.Start( );   // Does Mutex.WaitOne(Mutex gM1)      t3.Start( );   // Does Mutex.WaitAny(Mutex[] of gM1 and gM2)      t4.Start( );   // Does Mutex.WaitOne(Mutex gM2)      Thread.Sleep(2000);      Console.WriteLine(" - Main releases gM1");      gM1.ReleaseMutex( );  // t2 and t3 will end and signal      Thread.Sleep(1000);      Console.WriteLine(" - Main releases gM2");      gM2.ReleaseMutex( );  // t1 and t4 will end and signal      // Waiting until all four threads signal that they are done.      WaitHandle.WaitAll(evs);       Console.WriteLine("... Mutex Sample");   }   public void t1Start( )   {      Console.WriteLine("t1Start started,  Mutex.WaitAll(Mutex[])");      Mutex[] gMs = new Mutex[2];      gMs[0] = gM1;  // Create and load an array of Mutex for WaitAll call      gMs[1] = gM2;      Mutex.WaitAll(gMs);  // Waits until both gM1 and gM2 are released      Thread.Sleep(2000);      Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[]) satisfied");      Event1.Set( );      // AutoResetEvent.Set() flagging method is done   }   public void t2Start( )   {      Console.WriteLine("t2Start started,  gM1.WaitOne( )");      gM1.WaitOne( );    // Waits until Mutex gM1 is released      Console.WriteLine("t2Start finished, gM1.WaitOne( ) satisfied");      Event2.Set( );     // AutoResetEvent.Set() flagging method is done   }   public void t3Start( )   {      Console.WriteLine("t3Start started,  Mutex.WaitAny(Mutex[])");      Mutex[] gMs = new Mutex[2];      gMs[0] = gM1;  // Create and load an array of Mutex for WaitAny call      gMs[1] = gM2;      Mutex.WaitAny(gMs);  // Waits until either Mutex is released      Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])");      Event3.Set( );       // AutoResetEvent.Set() flagging method is done   }   public void t4Start( )   {      Console.WriteLine("t4Start started,  gM2.WaitOne( )");      gM2.WaitOne( );   // Waits until Mutex gM2 is released      Console.WriteLine("t4Start finished, gM2.WaitOne( )");      Event4.Set( );    // AutoResetEvent.Set() flagging method is done   }}

示例输出

Mutex Sample ... - Main Owns gM1 and gM2t1Start started,  Mutex.WaitAll(Mutex[])t2Start started,  gM1.WaitOne( )t3Start started,  Mutex.WaitAny(Mutex[])t4Start started,  gM2.WaitOne( ) - Main releases gM1t2Start finished, gM1.WaitOne( ) satisfiedt3Start finished, Mutex.WaitAny(Mutex[]) - Main releases gM2t1Start finished, Mutex.WaitAll(Mutex[]) satisfiedt4Start finished, gM2.WaitOne( )... Mutex Sample
注意   此示例的输出可能在每台计算机上以及每次运行时均各不相同。运行此示例的计算机的速度及其操作系统都能影响输出的顺序。在多线程环境中,事件可能并不按预期的顺序发生。

 
 

上一篇:C#&nbsp;程序员参考--不安全代码教程  下一篇:C#&nbsp;程序员参考--安全性教程