Hello All
I have written a sample program below.
class Program
{
static int x = 2;
static void Main(string[] args)
{
Console.WriteLine("Thread ID {0} and Main Called!", Thread.CurrentThread.ManagedThreadId);
ThreadPool.QueueUserWorkItem(Count, args);
ThreadPool.QueueUserWorkItem(Count2, args);
Console.WriteLine("Thread ID {0} and Main Done!", Thread.CurrentThread.ManagedThreadId);
Console.ReadLine();
}
static void Count(object args)
{
for (int i = 0; i < 10; i++)
{
x = x + 2;
Console.WriteLine("Thread ID {0} AND Count 1: " + x, Thread.CurrentThread.ManagedThreadId);
}
}
static void Count2(object args)
{
for (int i = 0; i < 10; i++)
{
x = x + 2;
Console.WriteLine("Thread ID {0} AND Count 2: " + x, Thread.CurrentThread.ManagedThreadId);
}
}
}
When calling the Count method using ThreadPool.QueueUserWorkItem, I noticed that Main is finished before the Count method completes and Count2 method gets tangled up with Count Method.
Is there anyway for Main (and Count2) to wait until the Count method has compleleted? I do not want to use a lock nor Thread.Sleep (since I dont know how long the Count operations will take). I have read somewhere async calls or WAIT is used for this time of situations.
Any ideas?