下面的代碼處理一個帶有2個參數的套接字消息。它將信息放入隊列並在另一個線程上處理。我的問題是,如果2個消息正好在另一個之後進入,然後出隊併發送到方法ProcessData,那麼ProcessData上是否存在爭用條件?隊列上的爭用條件
private void DataIn(long Code, string Message)
{
if (!Started)
{
if (DataInQueue == null)
DataInQueue = new Queue();
DataInThread = new Thread(new ThreadStart(ThreadProcedure));
DataInThreadEnding = false;
DataInThread.IsBackground = true;
DataInThread.Start();
Started = true;
}
DataInQueue.Enqueue(new cDataIn(Code, Message));
}
private void ThreadProcedure()
{
while (!ProgramEnding)
{
Queue mySyncdQ = Queue.Synchronized(DataInQueue);
if (mySyncdQ != null && mySyncdQ.Count > 0)
{
cDataIn data = null;
// Creates a synchronized wrapper around the Queue.
if (mySyncdQ.Count > 0)
data = (cDataIn)mySyncdQ.Dequeue();
ProcessData(data);
}
}
}
你是說有問題嗎? – Jon
Queue類的文檔(http://msdn.microsoft.com/zh-cn/library/system.collections.queue(v=VS.100).aspx)有一個關於線程安全的段落,實例成員不是TS。我沒有看過執行情況,看看有什麼變化,但你可以通過旋轉兩個線程來檢查自己。一個在順序消息中泵(1,2,3 ...),另一個讀取它們。你可能會得到一個例外或差距/雙打(1,2,2,4,5,...)。 – gjvdkamp
請參閱我上面的更新... – Yahia