2012-07-16 36 views
3

我們在深度抽象程序集中的某個地方存在從OperationContext.Current中讀取數據的WCF行爲,當此代碼從Task中執行時,OperationContext.Current爲空,是否可以在抽象程序集內部解決這個問題,還是需要向這個程序集的所有消費者添加一些代碼?在任務並行庫中保留OperationContext

+0

誰開始「任務」?消費者?在啓動「Task」之前是否執行了抽象程序集的任何代碼? – svick 2012-07-16 08:46:40

+0

不,這是問題,消費者開始的任務:( – 2012-07-16 09:07:08

回答

0

似乎是唯一的辦法就是添加一些的CallContext中,就像目前的主要存儲...

1

點在哪裏您創建Task instance,你應該使用一個封閉,像這樣:

// The operation context. 
OperationContext oc = OperationContext.Current; 

Task t = Task.Factory.StartNew(() => { 
    // Do something with context here, it will be valid for 
    // the life of the operation. 
}; 

您也可以撥打overload of StartNew這需要一個state參數並通過OperationContext instance中,鑄造和使用它需要在Task的時候,像這樣:

Task t = Task.Factory.StartNew(s => { 
    // s is an object, so need to cast here. 
    var oc = (OperationContext) c; 

    // Work with the OperationContext. 
}, 
// Note, this is passed to the delegate through the 's' parameter. 
OperationContext.Current); 

注意,在這兩種情況下,OperationContext只會有利於操作的使用壽命。該操作的完成應取決於Task的完成情況。

如果你推出一個Task將運行在操作完成後,那麼你應該從你的OperationContext需要的值那些複製到另一個結構的方式傳遞到Task進行處理。

+0

是的,我知道,但問題是不能強制消費者代碼不只是啓動一個任務,並做的東西:) – 2012-07-17 07:14:21

+0

@TimMahy然後,你似乎必須在抽象中構建上下文,並將其傳遞到需要的地方。 – casperOne 2012-07-17 11:49:45

2

正面臨着類似的問題。通過任務調用服務。 下面的代碼片斷解決了。 OperationContext.Current明確地通過在服務調用完成之前投射由Task提供的state變量來設置。

Task<int> taskContactsCount = Task.Factory.StartNew<int>((state) => 
     { 
      int count = 0; 
      try 
      { 
       OperationContext.Current = (OperationContext)state; 
       TestServiceClient testServiceProxy = new TestServiceClient(); 
       var count = testServiceProxy.GetCount(); 
      } 
      catch (Exception ex) 
      { 
      } 
      return contactsCount; 
     }, OperationContext.Current);