Alex Rivera | Logout

C# multi-threaded console application - Console quits before threads complete

Asked 2011-10-13T18:52:41.940
8

I have a c# console application that creates up to 5 threads.

The threads are executing fine, but the UI thread shuts down as it finishes its work.

Is there a way to keep the main UI thread running, for as long as the side threads are running?

foreach (var url in urls)
{
    Console.WriteLine("starting thread: " + url); 
    ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(myMethod), url);
}

I'm kicking off my threads as per the code above.

Edit
Report

3 Answers

9

The threads in the ThreadPool are background threads and that means an exiting application won't wait for them to complete.

You have a few options:

  • wait with for example a semaphore
  • wait on a counter with Sleep() , very crude but OK for a simple console app.
  • use the TPL, Parallel.ForEach(urls, url => MyMethod(url));
answered 2011-10-13T19:01:27.513
2

Ah - the ThreadPool is background. It is queued, but then your program ends. Finished. Program terminates.

Read up on Semaphores (WaitSignal) and wait- The threads in the callback at the end signal they are ended, when all have signaled that the main thread can continue.

answered 2011-10-13T18:57:56.033
-1

in Main:

var m = new ManualResetEvent(false);
// do something
foreach (var url in urls)
{
  Console.WriteLine("starting thread: " + url); 
  ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(myMethod), url);
}
m.WaitOne();


private static void myMethod(object obj)
{
  try{
   // do smt
  }
  finally {
    m.Set();
  }
}
answered 2011-10-13T19:09:09.493

Your Answer