C# multi-threaded console application - Console quits before threads complete
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));
If you are using .NET 4.0:
var tasks = new List<Task>();foreach(var url in urls){ tasks.Add(Task.Factory.StartNew(myMethod, url));}// do other stuff...// On shutdown, give yourself X number of seconds to wait for them to complete...Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(30));
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.