我有一個生產者 - 消費者模式爲一個產品工作。當生產者生產許多產品時,最好的實施是什麼?例如,消費者應該使用的DataBaseEvent,GuiEvent和ControlEvent。下面的代碼顯示了一個產品的模式(一個DataBaseEvent)。應該將每個事件類型排入隊列中,還是應該繼承可以排隊的基類。在處理很多事件類型時,可能存在更好的模式?生產者消費者模式,當很多產品
class DataBaseEventArgs : EventArgs
{
public string textToDB = "";
}
class Consumer
{
private Producer mProducer = new Producer();
private Queue<DataBaseEventArgs> mDataBaseEventQueue = new Queue<DataBaseEventArgs>();
private static EventWaitHandle mDataBaseEventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
private Thread mDataBaseEventDequeueThread = null;
public Consumer()
{
mDataBaseEventDequeueThread = new Thread(DataBaseDequeueEvent);
mDataBaseEventDequeueThread.Start();
mProducer.mDataBaseEventHandler += WhenDataBaseEvent;
}
protected void DataBaseDequeueEvent()
{
while (true)
{
DataBaseEventArgs e;
lock (((ICollection)mDataBaseEventQueue).SyncRoot)
{
if (mDataBaseEventQueue.Count > 0)
{
e = mDataBaseEventQueue.Dequeue();
}
}
// WriteToDatabase(e.textToDB);
if (mDataBaseEventQueue.Count == 0)
{
mDataBaseEventWaitHandle.WaitOne(1000);
mDataBaseEventWaitHandle.Reset();
}
}
}
internal void WhenDataBaseEvent(object sender, DataBaseEventArgs e)
{
lock (((ICollection)mDataBaseEventQueue).SyncRoot)
{
mDataBaseEventQueue.Enqueue(e);
mDataBaseEventWaitHandle.Set();
}
}
}
class Producer
{
public event EventHandler<DataBaseEventArgs> mDataBaseEventHandler = null;
public void SendDataBaseEvent()
{
if (mDataBaseEventHandler != null)
{
DataBaseEventArgs e = new DataBaseEventArgs();
e.textToDB = "This text will be written to DB";
mDataBaseEventHandler(this, e);
}
}
}
感謝您的監視器代碼示例。我認爲我會使用它來代替EventWaitHandler。 – humcfc 2008-11-17 13:39:17