开发者

Problem in thread pool implementation(C#3.0)

开发者 https://www.devze.com 2023-01-03 07:08 出处:网络
I have done the below thread pool program but the problem is that the WaitCallBackMethod(here ThreadPoolCallback) is getting called 2 times(which ideally should be called 1ce). what is the misktake I

I have done the below thread pool program but the problem is that the WaitCallBackMethod(here ThreadPoolCallback) is getting called 2 times(which ideally should be called 1ce). what is the misktake I am making?

public class Calculation
    {
         #region Private variable declaration
           ManualResetEvent[] factorManualResetEvent = null;
         #endregion

        public void Compute()
        {                
                factorManualResetEvent = new ManualResetEvent[2];

                for (int i = 0; i <开发者_如何学编程 2; i++){ 
                factorManualResetEvent[i] = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(ThreadPoolCallback, i);}


           //Wait for all the threads to complete
           WaitHandle.WaitAll(factorManualResetEvent);  

         //Proceed with the next task(s)  
        NEXT_TASK_TO_BE_EXECUTED();        
       }

       #region Private Methods

        // Wrapper method for use with thread pool.
        public void ThreadPoolCallback(Object threadContext)
        {
            int threadIndex = (int)threadContext;
            Method1();
            Method2();          
           factorManualResetEvent[threadIndex].Set();
        }

        private void Method1 ()
            { //Code of method 1}

        private void Method2 ()
            { //Code of method 2 }

        #endregion
}

If I do

//Initializang all the manual reset events first
Enumerable.Range(0, exposureManualResetEvent.Length).ToList().ForEach(i =>
{
  exposureManualResetEvent[i] = new ManualResetEvent(false);
 });

Enumerable.Range(0, 1).ToList().ForEach(i =>
{
ThreadPool.QueueUserWorkItem(ExposureThreadPoolCallback, i);
});

The program gets hang!

I am using C#3.0 Thanks


Well, think of ThreadPoolCallback as the ThreadProc for each thread you execute (ThreadPool.QueueUserWorkItem() starts a new thread each time you call it.).

Since you are Queuing 2 threads, you're going to get two calls to the Proc.


You are calling it twice:

for (int i = 0; i < 2; i++)
{ 
    factorManualResetEvent[i] = new ManualResetEvent(false);
    ThreadPool.QueueUserWorkItem(ThreadPoolCallback, i);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消