2012-06-05 82 views
4

我正在嘗試WCF事務實現,並且提出了WCF 4.0是否支持異步事務的想法。WCF是否支持異步操作在TransactionScope中調用?

例如, 我有幾個服務操作啓用客戶端\服務事務,在客戶端,我使用TransactionScope並在事務中,我創建任務以異步調用這些操作。

在這種情況下,我假設交易會正常工作,對嗎?

回答

0

我非常懷疑。看起來如果你開始ascync操作,你不再參與原始交易。

我寫了一個小測試LINQPad

void Main() 
{ 
    using (var scope = new TransactionScope(TransactionScopeOption.Required)) 
    { 
    try 
    { 
     Transaction.Current.Dump("created"); 
     Task.Factory.StartNew(Test); 
     scope.Complete(); 
    } 
    catch (Exception e) 
    { 
    Console.WriteLine(e); 
    } 
    Thread.Sleep(1000); 
} 

Console.WriteLine("closed"); 
Thread.Sleep(5000); 
} 


public void Test() 
{ 
using (var scope = new TransactionScope(TransactionScopeOption.Required)) 
    { 
    Transaction.Current.Dump("test start"); // null 
    Thread.Sleep(5000); 
    Console.WriteLine("done"); 
    Transaction.Current.Dump("test end"); // null 
    } 
} 
+0

查看我的解答。 –

0

你需要創建的任務同時設置的OperationContext和Transaction.Current。

更具體地說,在服務你需要做的是這樣的:

public Task ServiceMethod() { 
    OperationContext context = OperationContext.Current; 
    Transaction transaction = Transaction.Current; 

    return Task.Factory.StartNew(() => { 
     OperationContext.Current = context; 
     Transaction.Current = transaction; 

     // your code, doing awesome stuff 
    } 
} 

這得到重複,你可能會懷疑,所以我建議你寫它的幫手。