Event类,这个类与事件是不一样的。一共有四种。ManualResetEvent,AutoResetEvemt,ManualResetEventSlim,CountdownEvent类。
class Program
{
static void Main(string[] args)
{
int taskCount = 6;
Calculator[] tasks = new Calculator[taskCount];
//发出事件信号和等待信号是成对出现的。一对一的处理。这样做的好处是线程不用都完成了再处理。
//完成一个处理一个。性能要好一些。
ManualResetEventSlim[] mEvents = new ManualResetEventSlim[taskCount];
WaitHandle[] handls = new WaitHandle[taskCount];
for (int i = 0; i < taskCount; i++)
{
int currentI = i;//需要在循环中取得i的值,因为当Task.Run运行时,在读取i的值的时候,有可能i已经超出了允许循环值,但程序会错误地将值赋予Task。
mEvents[i] = new ManualResetEventSlim(false);//给数组实例化,并将初始信号设置为false.
handls[i] = mEvents[i].WaitHandle;//发出与等待信号进行配对.
tasks[i] = new Calculator(mEvents[currentI]);
Task.Run(() => tasks[currentI].Calculation(i + 1, i + 3));
}
for (int i = 0; i < taskCount; i++)
{
int index = WaitHandle.WaitAny(handls);//等待任何一个线程执行完毕,并把索引返回给index。也有可能会返回超时错误的值。
if (index == WaitHandle.WaitTimeout)//获得的值如果是超时的值
{
Console.WriteLine("TimeOut");
}
else
{
mEvents[index].Reset();//终止信号.
Console.WriteLine("Task {0} is finisthed!,the reslut is {1}", index, tasks[index].result);
}
}
Console.WriteLine("Task is Completed");
Console.ReadKey();
}
}
/// <summary>
/// 设计一个类,使其计算后发出信号,逾期依赖的程序能够往下运行.
/// </summary>
class Calculator
{
public int result { get; private set; }
private ManualResetEventSlim mEvent;
public Calculator(ManualResetEventSlim ev)
{
this.mEvent = ev;
}
public void Calculation(int x, int y)
{
Console.WriteLine("Task {0} is start calculation",Task.CurrentId);
Thread.Sleep(new Random().Next(3000));
this.result = x + y;
Console.WriteLine("Task {0} is ready",Task.CurrentId);
mEvent.Set();//计算完成,发出信号,使其等待的程序能够运行.
}
}