以下のコードを検討してください。の複数のインスタンスを作成したくありません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();
}
}
上記のコードに2つの問題があります
1>アプリケーションがないと、 Console.Read()
すべてのスレッドが終了する前にアプリケーションが終了します。
2>ステートメント Console.WriteLine("All threads complete");
が2回実行されます。
これを修正するにはどうすればよいですか?