考虑下面的代码。我不想创建多个class Waiter
. (所以我不能使用 ManualResetEvent 类)
using System;
using System.Threading;
public class Waiter
{
static int counter=0;
static int max=20;
public void Start()
{
for (int i = 1; i <= max; i++)
{
ThreadPool.QueueUserWorkItem(DoWork, (object)i);
}
Console.Read();//without this line the application quits before all threads are complete :(
}
public void DoWork(object o)
{
try
{
Thread.Sleep(1000);
}
finally
{
counter++;
Console.WriteLine(counter);
if (counter==max )
{
Console.WriteLine("All threads complete");
}
}
}
}
public class ThreadPoolExample
{
static void Main()
{
Waiter wtr=new Waiter();
wtr.Start();
}
}
上面的代码有两个问题
1>如果 Console.Read()
应用程序在所有线程结束之前退出。
2>语句 Console.WriteLine("All threads complete");
执行两次。
我该如何解决?