本文转载连接: https://www.cnblogs.com/DonetRen/p/10177339.html
在使用线程池时,当用线程池执行多个任务时,由于执行的任务时间过长,会导制两个任务互相执行,如果两个任务具有一定的操作顺序,可能会导制不同的操作结果,这时,就要将线程池按顺序操作。下面先给一段代码,该代码是不按顺序对线程池进行操作的,代码如下:
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方法后,将当前线程设置为终止状态,执行其他等待的线程。修改后的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
运行结果如下: |