标签:sea use 其他 rem callback eve void lock wait
internal sealed class AClass
{
public int Method(int num)
{
Thread.Sleep(1000);
return num * num;
}
public void UsingCallback(int numToDo)
{
int[] squares = new int[numToDo];
AutoResetEvent done = new AutoResetEvent(false);
//在其他线程上执行任务
for(int n = 0; n < squares.Length; n++)
{
ThreadPool.QueueUserWorkItem(
obj => {
int num = (int)obj;
squares[num] = Method(num);
//最后一个任务,就让主线程继续运行
if(Interlocked.Decrement(ref numToDo) == 0)
{
done.Set();
}
},n);
}
//等待其他所有线程结束运行
done.WaitOne();
for(int n = 0; n < squares.Length; n++)
{
Console.WriteLine("Index{0},Square{1}", n, squares[n]);
}
}
}
标签:sea use 其他 rem callback eve void lock wait
原文地址:http://www.cnblogs.com/blogs-cjz/p/7417876.html