2012-04-04 173 views
33

什麼是淨ConcurrentQueueBlockingCollection之間的區別是什麼?.Net中的ConcurrentQueue和BlockingCollection之間有什麼區別?

爲什麼BlockingCollection是最好的生產者 - 消費者操作時,它可以通過ConcurrentQueue做什麼?我是否需要改進以下代碼中的任何內容?

MessageSlotMachineGameStartOrAndStatusUpdate msg; 

while (!aCancellationToken.IsCancellationRequested) 
{ 
    try 
    { 
     this.isStillConsumingMsg = true; 
     Boolean takeResult = this.msgQueue.TryTake(out msg, this.msgConsumeTimeOut, aCancellationToken); 
     if (takeResult) 
     { 
      if (msg != null) 
      { 
       this.ProcessMessage(msg); 
      } 
     } 
     else 
     { 
      break; 
     } 
    } 
    catch (OperationCanceledException err) 
    { 
     EngineManager.AddExceptionLog(err, "Signal Operation Canceled"); 
    } 
    catch (Exception err) 
    { 
     EngineManager.AddExceptionLog(err, "Signal exception"); 
    } 
    finally 
    { 
     this.isStillConsumingMsg = false; 
    } 
} 

回答

35

BlockingCollectionTake方法,將阻止消費者如果有一件什麼東西,並等待制片方提供的項目。 ConcurrentQueue缺乏這樣的方法 - 如果它是空的,消費者需要處理等待,並且生產者需要提供非空通知。

+0

你可以給我的通知可以怎樣做樣品。 – 2012-04-04 12:27:02

+1

@WAPGuy您可以使用['AutoResetEvent'(http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx)。按照鏈接並向下滾動以查看如何使用它的示例。 – dasblinkenlight 2012-04-04 12:32:52

+0

好的,當它發信號給WaitHandle?立即當它是空的或在Take方法給出的超時之後? – 2012-04-04 12:39:48

相關問題