問題描述
我想知道在處理多線程時如何以正確的方式使用 TransactionScope 類?
I was wondering how you would use the TransactionScope class in the correct way when you are dealing with multithreading?
我們在主線程中創建了一個新的作用域,然后我們產生了幾個工作線程,我們希望這些線程參與到主作用域中,例如,如果作用域從未完成,則在每個工作線程上調用回滾.
We create a new scope in our main thread and then we spawn off a couple of worker threads and we want these to participate in the main scope, so that for example the rollback is called on each worker if the scope is never completed.
我在內部使用 ThreadStaticAttribute 閱讀了有關 TransactionScope 的內容,這使得上述操作變得不可能/非常困難 - 有人可以驗證任何一種方式嗎?如果我們以同步方式運行代碼,則回滾工作,即內部事務能夠參與主事務,但如果我們切換到線程執行則不行.
I read something about TransactionScope using the ThreadStaticAttribute internally which made the above impossible / very difficult - could someone verify either way? If we run our code in a synchronized fashion then the rollbacks work, i.e the inner transactions are able to participate in the main transaction, but not if we switch over to a threaded execution.
推薦答案
參見 MSDN:
您還應該使用 TransactionScope 和DependentTransaction 類需要使用的應用程序同一筆交易跨多個函數調用或多線程電話.
You should also use the TransactionScope and DependentTransaction class for applications that require the use of the same transaction across multiple function calls or multiple thread calls.
所以也許看看 DependentTransaction
- 特別是,有一個工作線程示例,這里.
So maybe look into DependentTransaction
- in particular, there is a worker thread example, here.
這篇關于TransactionScope 和多線程的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!