2017-02-09 54 views
-1

我使用併發隊列,並通過創建Action委託併發隊列離隊

Action action =() => 
     { 
      SubscriptionResponseModel subsModel; 
      while (concurrentQueue.TryTake(out subsModel)) 
      { 
       MakeTransactionAndAddIntoQueue(subsModel); 
      } 
     }; 

出列,通過多線程隊列中的數據,並調用這個動作代表並行多線程

Parallel.Invoke(action, action, action, action, action, action, action, action, action, action, action, action, action, action, action); 

我想知道有一件事,當我在多個動作中使用SubscriptionResponseModel subsModel;時它是線程安全的嗎?

+0

什麼是SubscriptionResponseModel – Trey

+2

這取決於*您*執行'SubscriptionResponseModel' –

回答

1

action的每個調用都有自己的subsModel - 因此使用它從隊列中獲取值是線程安全的。

情況下它不會被線程安全是當你捕獲從外面方面變量:

// ********** Code showing non-thread safe case ************** 
    SubscriptionResponseModel subsModel; 
    Action action =() => 
    { 
     // all invocations of `action` will share subsModel as it is captured. 
     while (concurrentQueue.TryDequeue(out subsModel)) 
     { 
      MakeTransactionAndAddIntoQueue(subsModel); 
     } 
    }; 

注:

  • 無論是否使用性能/的SubscriptionResponseModel的方法是線程安全取決於該類型。
  • 並行運行多個TryDequeue很有可能不會提高性能。多個繁忙循環的Parallel.Invoke只會阻止多個線程不斷查詢空隊列。
+0

如果我想我們平行怎麼可以這樣消耗我的併發隊列?在上面的例子中,我正在做的是正確的方式嗎?請建議 –

+0

@maheshsharma你在帖子中的代碼實現你想要的。你的任務是否真的有用,取決於你。你可能想單獨問一個關於實現你的實際目標的更好的方法(你的代碼的整個點不太可能「並行地使用我的併發隊列」 - 如果提出新的問題,請確保添加真實的使用場景) –