2010-06-09 101 views
0

我已经完成了下面的线程池程序,但问题是WaitCallBackMethod(这里是ThreadPoolCallback)被调用2次(理想情况下应该被称为1ce)。我在做什么错事?线程池实现问题(C#3.0)

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 
} 

如果我做

//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); 
}); 

程序被挂!

我使用C#3.0 感谢

回答

0

嗯,你ThreadPoolCallback作为ThreadProc的为每个线程在执行(ThreadPool.QueueUserWorkItem()开始每次调用它一个新的线程)。

既然你是排队2线程,你会得到两个调用Proc。

+0

那么我应该怎么办序得到它的工作..请帮助 – Newbie 2010-06-09 07:14:45

+0

我不知道你想,虽然做的 - 如果你只处理一件事一段时间,你在等待它正在处理,为什么不只是同步(没有线程)? – RobS 2010-06-09 08:09:22

0

你两次调用它:

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

那么我应该怎么做,才能得到它的工作..请帮助 – Newbie 2010-06-09 07:10:21