Aldrich Blog

C# | BizTalk

C# Using ThreadPool for Multi-Threaded Application

I'm currently designing an application specifically to handle multiple processing at a certain time. I've read all articles about threading, whether to use a background worker, custom thread management, or by using a thread pool. What facinates me is the thread pool, just by passing a workitem viola you have a working multi-threaded application. See simple example below:

using System;
using System.Threading;

public class MyProcess
{

    private ManualResetEvent _doneEvent;

    public MyProcess(ManualResetEvent doneEvent)
    {
        _doneEvent = doneEvent;
    }

    public void MyProcessThreadPoolCallback(Object threadContext)
    {
        int threadIndex = (int)threadContext;
        Console.WriteLine("thread {0} started...", threadIndex);
        StartProcess();
        Console.WriteLine("thread {0} end...", threadIndex);

    // Indicates that the process had been completed
        _doneEvent.Set();
    }


    public void StartProcess()
    {
        // TODO: Add code for processing here

    }

  
}

public class ThreadPoolExample
{
    static void Main()
    {
        const int totalCountToProcess = 10;
        
        ManualResetEvent[] doneEvents = new ManualResetEvent[totalCountToProcess];
        MyProcess[] MyProcessArray = new MyProcess[totalCountToProcess];
      
        // Configure and launch threads using ThreadPool:
        Console.WriteLine("launching tasks...");
        for (int i = 0; i < totalCountToProcess ; i++)
        {
            doneEvents[i] = new ManualResetEvent(false);
            MyProcess p = new MyProcess(doneEvents[i]);
            MyProcess[i] = p;
            ThreadPool.QueueUserWorkItem(p.MyProcessThreadPoolCallback, i);
        }

        // Wait for all threads in pool to finished processing

        WaitHandle.WaitAll(doneEvents);
        Console.WriteLine("All Process are complete.");

           }
}

Legacy Comments


kibble
2007-05-15
re: C# Using ThreadPool for Multi-Threaded Application
I get these errors:
error CS0118: 'MyProcess' is a 'type' but is used like a 'variable'
error CS0117: 'ThreadPool' does not contain a definition for
'QueueUserWorkItem'

To fix the first one [CS0118] change the line "MyProcess[i] = p;" to "MyProcessArray[i] = p;"

But I'm unsure how to resolve the second error.

Kam
2007-06-08
re: C# Using ThreadPool for Multi-Threaded Application
But I thought that the Threadpool shared its resources with tother processes and it was possible (becasue of the 25 thread limit) to create deadlocks and mess up other processes? Especially where you have long running tasks (5 seconds +).

PLease correct me if I'm wrong and why I am wrong - because I am having serious b*llache writing a manager for myself.

Thanks