Skip to main content

In .NET, ThreadPool threads won't return without setting up ManualResetEvents or AutoResetEvents. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such.

public static void MultiThreadedTest1()
{
    Thread[] threads = new Thread[count];

    for (int i = 0; i < threads.Length; i++)
    {
        threads[i] = new Thread(DoSomeWork());
    }

    foreach(Thread thread in threads)
    {
        thread.Start();
    }

    foreach(Thread thread in threads)
    {
        thread.Join();
    }
}

//
// Option 2: replace DoSomeWork() with anonymous method.
//

public static void MultiThreadedTest2()
{
    Thread[] threads = new Thread[10];

    for (int i = 0; i < threads.Length; i++)
    {
        int index = i;
        threads[i] = new Thread(() =>
        {
            // anon. thread worker
            Console.WriteLine(
                "{0}/{1}: {2}", index, Thread.CurrentThread.ManagedThreadId,
                "Doing work..."
            );
            Thread.Sleep(500);// simulate work...
        });
    }

    foreach (Thread thread in threads)
    {
        thread.Start();
    }

    foreach (Thread thread in threads)
    {
        thread.Join();
    }
}