在使用線程池時,當用線程池執行多個任務時,由於執行的任務時間過長,會導制兩個任務互相執行,如果兩個任務具有一定的操作順序,可能會導制不同的操作結果,這時,就要將線程池按順序操作。下面先給一段代碼,該代碼是不按順序對線程池進行操作的,代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), autoEvent);
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), autoEvent);
Console.ReadLine();
}
static void ThreadMethod(object stateInfo)
{
for (int i = 0; i < 100;i++ )
Console.WriteLine("ThreadOne, executing ThreadMethod, " + "is {0}from the thread pool.", Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");
}
static void WorkMethod(object stateInfo)
{
for (int i = 0; i < 100; i++)
Console.WriteLine("ThreadTwo, executing WorkMethod");
}
}
}
運行結果如圖1、圖2所示。

圖1 運行結果的上半部

圖2 運行結果的下半部
從圖1、圖2可以看出,在使用線程池對線程進行操作時,由於各任務的時間過長,多個任務的線程可能會交互操作,那么,如何才能將線程池按指定的順序進行操作呢?主要是用AutoResetEvent類來實現的。
可以用AutoResetEvent類的WaitOne方法阻止線程,然后只執行當前操作的線程池,當遇到AutoResetEvent類的Set方法后,將當前線程設置為終止狀態,執行其他等待的線程。修改后的代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), autoEvent);
autoEvent.WaitOne();
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), autoEvent);
autoEvent.WaitOne();
Console.ReadLine();
}
static void ThreadMethod(object stateInfo)
{
for (int i = 0; i < 100;i++ )
Console.WriteLine("ThreadOne, executing ThreadMethod, " + "is {0}from the thread pool.", Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");
((AutoResetEvent)stateInfo).Set();
}
static void WorkMethod(object stateInfo)
{
for (int i = 0; i < 100; i++)
Console.WriteLine("ThreadTwo, executing WorkMethod");
((AutoResetEvent)stateInfo).Set();
}
}
}
運行結果如下:

