2009-10-14 100 views
1

我是一個初學者。基於Albahari的生產者/消費者解決方案,我開發了一個代碼。編碼工作正常。但我對我的實現有一些懷疑。.NET:澄清請求 - 處理線程

class FloodDisaterManagement :IDisposable 
    { 

     Queue<string>MedicinePack = new Queue<string>(); 
     Thread[] volunteers; 
     readonly object locker = new object(); 

    public FloodDisaterManagement(int volunteerCount) 
    { 
     volunteers = new Thread[volunteerCount]; 

     for (int i = 0; i < volunteerCount; i++) 
     { 
      volunteers[i] = new Thread(SupplyMedicine); 
      volunteers[i].Start(); 
     } 
    } 

    public void DumpMedicine(string pack) 
    { 
     lock (locker) 
     { 
      MedicinePack.Enqueue(pack); 
      Monitor.PulseAll(locker); 
     } 
    } 

    public void Dispose() 
    { 

     foreach (Thread volunteer in volunteers) DumpMedicine(null); 
     foreach (Thread volunteer in volunteers) volunteer.Join(); 
    } 

    public void SupplyMedicine() 
    { 
     while (true) 
     { 
      string pack; 
      lock (locker) 
      { 
       while (MedicinePack .Count == 0) Monitor.Wait(locker); 
       pack= MedicinePack.Dequeue(); 
      } 
      if (pack == null) return; 
      Console.WriteLine(pack+"is supplied"); 
      Thread.Sleep(1000); 
     } 

    } 


    static void Main() 
    { 
     string[] medicinePacks = new string[] 
     { "Pack1", "Pack2", "Pack3", "Pack4", "Pack5", "Pack6", 
      "Pack7", "Pack8", "Pack9", "Pack10" 
     }; 

     using (FloodDisaterManagement q = new FloodDisaterManagement(2)) 
     { 
      foreach (string pack in medicinePacks) 
       q.DumpMedicine(pack); 
      Console.WriteLine("Enqueued 10 Medicine Packs"); 

     } 

     Console.WriteLine("..Medicines Distribution Completed"); 
     Console.ReadKey(true); 
    } 


} 

問題:


  1. 正如我們已經使用(...)在main(),爲什麼仍然有需要的Dispose()在 FloodDisasterManagement類?
  2. Dispose()中有兩個foreach的確切目的是什麼?
  3. 哪裏控制返回時,我們使用 「return語句」 的 SupplyMedicine裏面()? (即)
public void SupplyMedicine() 
{ 
    while (true) 
    { 
     .... 
     if (pack == null) return; 
     ... 
     //Whether the control return to Main() or SomeWhere? 
    } 

} 

回答

3

1:因爲using呼叫Dispose();這就是using的目的。 2:關閉每個封裝的資源,在這種情況下,線程(要求它們退出,然後等待它們退出)。

3:它返回給調用者;在這種情況下,調用者是Thread,所以這完全退出線程

或英文:

  • using在這種情況下行爲,等待所有線程退出;沒有using我們將關閉太早
  • foreach信號,每個線程退出時,它已經處理完其負載,並等待他們全部
  • null被檢測爲「立即退出」信號,導致每個線程出口
+0

非常感謝Marc。 – user186973 2009-10-14 20:34:25

1

約爲3:

由於SupplyMedicine方法在一個單獨的線程中運行,這是運行第一個也是唯一方法thread- return語句只是意味着該線程完成其工作,並應被終止(或返回到t如果你正在使用線程池線程,他會使用線程池)。

+0

非常感謝 – user186973 2009-10-14 20:35:07