我是一个初学者。基于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);
}
}
问题:
- 正如我们已经使用(...)在main(),为什么仍然有需要的Dispose()在 FloodDisasterManagement类?
- Dispose()中有两个foreach的确切目的是什么?
- 哪里控制返回时,我们使用 “return语句” 的 SupplyMedicine里面()? (即)
public void SupplyMedicine()
{
while (true)
{
....
if (pack == null) return;
...
//Whether the control return to Main() or SomeWhere?
}
}
非常感谢Marc。 – user186973 2009-10-14 20:34:25