Skip to main content
 首页 » 编程设计

c#之.NET : Clarification Request -Processing Threads

2024年02月24日36thcjp

我是初学者,基于Albahari的Producer/Consumer Solution,我开发了一个代码,编码工作正常,但我对我的实现有一些疑问。

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() 中有 Using(...) ,为什么仍然需要 Dispose() 在 洪水灾害管理类?
  2. 在 Dispose() 中有两个 foreach 的确切目的是什么?
  3. 当我们在内部使用“返回语句”时,控件返回到哪里 供应药物()? (即)
public void SupplyMedicine() 
{ 
    while (true) 
    { 
        ....   
        if (pack == null) return;  
        ...  
       //Whether the control return to Main() or SomeWhere? 
    } 
 
} 

请您参考如下方法:

1: 因为 using 调用 Dispose();这就是 using 的目的。

2:关闭每个封装的资源,在本例中为线程(要求它们退出,然后等待它们退出)。

3:它返回给调用者;在这种情况下,调用者是一个 Thread,所以这会干净地退出线程

或者英文:

  • 使用在这种情况下等待所有线程退出;如果没有 using,我们会过早关闭
  • foreach 向每个线程发出信号,让其在处理完负载后退出,并等待所有线程
  • null 被检测为“现在退出”信号,导致每个线程退出