本文介紹了如何在可取消的 async/await 中處理 TransactionScope?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試使用新的 async/await 功能來異步處理數據庫.由于某些請求可能很長,我希望能夠取消它們.我遇到的問題是 TransactionScope
顯然具有線程關聯性,而且似乎在取消任務時,它的 Dispose()
在錯誤的線程上運行.
I'm trying to use the new async/await feature to asynchronously work with a DB. As some of the requests can be lengthy, I want to be able to cancel them. The issue I'm running into is that TransactionScope
apparently has a thread affinity, and it seems that when canceling the task, its Dispose()
gets ran on a wrong thread.
具體來說,當調用 .TestTx()
時,我在 task.Wait ()
上得到以下 AggregateException
包含 InvalidOperationException
代碼>:
Specifically, when calling .TestTx()
I get the following AggregateException
containing InvalidOperationException
on task.Wait ()
:
"A TransactionScope must be disposed on the same thread that it was created."
代碼如下:
public void TestTx () {
var cancellation = new CancellationTokenSource ();
var task = TestTxAsync ( cancellation.Token );
cancellation.Cancel ();
task.Wait ();
}
private async Task TestTxAsync ( CancellationToken cancellationToken ) {
using ( var scope = new TransactionScope () ) {
using ( var connection = new SqlConnection ( m_ConnectionString ) ) {
await connection.OpenAsync ( cancellationToken );
//using ( var command = new SqlCommand ( ... , connection ) ) {
// await command.ExecuteReaderAsync ();
// ...
/
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!