如何在可取消的 async/await 中处理 TransactionScope?

时间:2022-11-03
本文介绍了如何在可取消的 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 ();
            //  ...
            /