views:

37

answers:

1

I'm struggling to understand why nothing is output using the following:

class Program
{
    static int m_Active = 500;
    static void Main(string[] args)
    {
        ThreadPool.SetMaxThreads(5, 5);
        Enumerable.Range(1, m_Active).ToList<int>()
            .ForEach(i => ThreadPool.QueueUserWorkItem((o) => { DoWork(i); }));
    }

    private static void DoWork(int i)
    {
        new Action(() => { Console.WriteLine(i); }).Invoke();
        if (Interlocked.Decrement(ref m_Active).Equals(0))
            new Action(() => { Console.WriteLine("Done"); }).Invoke();
    }
}
+7  A: 

Because your program terminates before it has any time to execute the threads. Adding a simple

Console.ReadLine();

at the end of the Main method should do just fine.

Darin Dimitrov
Yep. The key to the problem is that the ThreaPool threads are background threads, so they don't prevent the process from exiting.
Thomas Levesque