C# Execute Method (with Parameters) with ThreadPool

Posted by washtik on Stack Overflow See other posts from Stack Overflow or by washtik
Published on 2010-04-19T23:41:46Z Indexed on 2010/04/19 23:43 UTC
Read the original article Hit count: 359

We have the following piece of code (idea for this code was found on this website) which will spawn new threads for the method "Do_SomeWork()". This enables us to run the method multiple times asynchronously.

The code is:

    var numThreads = 20;
    var toProcess = numThreads;

    var resetEvent = new ManualResetEvent(false);

    for (var i = 0; i < numThreads; i++)
    {
        new Thread(delegate()
        {
            Do_SomeWork(Parameter1, Parameter2, Parameter3);
            if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set();
        }).Start();
    }

    resetEvent.WaitOne();

However we would like to make use of ThreadPool rather than create our own new threads which can be detrimental to performance. The question is how can we modify the above code to make use of ThreadPool keeping in mind that the method "Do_SomeWork" takes multiple parameters and also has a return type (i.e. method is not void).

Also, this is C# 2.0.

© Stack Overflow or respective owner

Related posts about c#

Related posts about threadpool