Consider the code below. I do not want to create multiple instances of class Waiter. (So I cannot use ManualResetEvent class)
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();
}
}
I have two problems with the above code
1>Without the Console.Read() the application quits before all threads end.
2>The statement Console.WriteLine("All threads complete"); executes twice.
How do I fix this?
Use Tasks instead, and then you can do Task.WaitAll(tasks);
Also, instantiate your tasks through the factory:
It will use the thread pool for you.