2012-11-14 59 views
0

以下是我的代碼,等待所有方法始終在等待。C#WaitHandle.WaitAll()始終在等待

class Program 
    { 
     static StreamWriter _fileStream; 
     static void Main(string[] args) 
     { 
      _fileStream = File.CreateText(@"C:\Praveen\HelloThread.txt"); 
      List<ManualResetEvent> meList = new List<ManualResetEvent>(); 
      ManualResetEvent currentEvent = new ManualResetEvent(true); 
      ManualResetEvent nextEvent = new ManualResetEvent(false); 
      meList.Add(currentEvent); 
      int length = 10; 
      Data data = null; 
      Console.WriteLine("Writing started..."); 
      for (int i = 0; i < length; i++) 
      { 
       data = new Data { CurrentEvent = currentEvent, Number = i, NextEvent = nextEvent }; 
       ThreadPool.QueueUserWorkItem(PrintMsg, data); 
       meList.Add(nextEvent); 
       currentEvent = nextEvent; 
       nextEvent = nextEvent = new ManualResetEvent(false); 
      } 

      CloseAll(meList); 
      Console.ReadLine(); 
     } 

     private static void CloseAll(List<ManualResetEvent> meList) 
     { 
      Console.WriteLine("Requested to close all..."); 
      while (WaitHandle.WaitAll(meList.ToArray())) 
      { 

      } 

      Console.WriteLine("Done with the writing..."); 
     } 

     private static void PrintMsg(object state) 
     { 

      Data data = state as Data; 

      data.CurrentEvent.WaitOne(); 

      string msg = "Hello times..."; 
      for (int j = 0; j < 5; j++) 
      { 
       _fileStream.WriteLine(msg + data.Number); 
       Console.WriteLine(msg + data.Number); 
      }   
      data.NextEvent.Set(); 
     } 
    } 

    public class Data 
    { 
     public ManualResetEvent CurrentEvent { get; set; } 
     public ManualResetEvent NextEvent { get; set; } 
     public int Number { get; set; } 
    } 

這是怎麼回事,它爲什麼總是在等待,有什麼想法?

+0

這個最終目標是什麼?您正在啓動線程但序列化他們的工作,這看起來更像生產者 - 消費者,您可以擁有單個工作線程並使用ConcurrentQueue來存儲工作項目。 – pstrjds

+0

當我看到像這樣的代碼nextEvent = nextEvent = new ManualResetEvent(false);我傾向於認爲作者並沒有真正地看待自己的代碼。目前還不清楚你實際上想做什麼。 –

回答

1

您在CloseAll方法中有無限循環。 WaitAll返回true當所有事件信號。您不需要空的while循環,只需添加該行:

WaitHandle.WaitAll(meList.ToArray());