C#多线程之线程池ThreadPool详解

  // TaskInfo contains data that will be passed to the callback method.

  public class TaskInfo

  {

  public RegisteredWaitHandle Handle = null;

  public string OtherInfo = "default";

  }

  public static void Main(string[] args)

  {

  // 主线程使用AutoResetEvent来给已注册的等待句柄发信号, 此等待句柄执行回调方法

  AutoResetEvent ev = new AutoResetEvent(false);

  TaskInfo ti = new TaskInfo();

  ti.OtherInfo = "First task";

  // The TaskInfo for the task includes the registered wait handle returned by RegisterWaitForSingleObject. This

  // allows the wait to be terminated when the object has been signaled once (see WaitProc).

  ti.Handle = ThreadPool.RegisterWaitForSingleObject(

  ev,

  new WaitOrTimerCallback(WaitProc),

  ti,

  1000,

  false

  );

  // 主线程等待三秒,为了演示队列中的线程超时,然后发信号.

  Thread.Sleep(3100);

  Console.WriteLine("Main thread signals.");

  ev.Set();//发信号

  // The main thread sleeps, which should give the callback method time to execute. If you comment out this line, the program usually ends before the ThreadPool thread can execute.

  Thread.Sleep(1000);

  // If you start a thread yourself, you can wait for it to end by calling Thread.Join. This option is not available with thread pool threads.

  }

  //The callback method executes when the registered wait times out,

  //or when the WaitHandle (in this case AutoResetEvent) is signaled.

  //WaitProc unregisters the WaitHandle the first time the event is signaled.

  public static void WaitProc(object state, bool timedOut)

  {

  TaskInfo ti = (TaskInfo)state;

  string cause = "TIMED OUT";

  if (!timedOut) //如果Timeout为false,表示接收到的信号后执行的

  {

  cause = "SIGNALED";

  //如果回调方法执行的话是因为WaitHandle触发信号的话,则用反注册等待句柄来取消回调方法将来的执行。

  if (ti.Handle != null)

  ti.Handle.Unregister(null);//

  }

  Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",

  ti.OtherInfo, Thread.CurrentThread.GetHashCode().ToString(), cause);//超时后执行的

  }