C# Execute Method (with Parameters) with ThreadPool C# Execute Method (with Parameters) with ThreadPool multithreading multithreading

C# Execute Method (with Parameters) with ThreadPool


Pretty much the same way, but use a WaitCallback passed to ThreadPool.QueueUserWorkItem:

var numThreads = 20;var toProcess = numThreads;var resetEvent = new ManualResetEvent(false);for (var i = 0; i < numThreads; i++){    ThreadPool.QueueUserWorkItem (        new WaitCallback(delegate(object state) {        Do_SomeWork(Parameter1, Parameter2, Parameter3);        if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set();    }), null);}resetEvent.WaitOne();


With C# 2.0, you call

ThreadPool.QueueUserWorkItem(callback, new object[] { parm1, parm2, etc });

Then inside the callback you cast the object[] back into the correct parameters and types. Regarding the return type, if using the ThreadPool I don't think you will be able to get the return value, the callback has to have a signature of

void Callback (object parm)