How to dispose TransactionScope in cancelable async/await?(如何在可取消的 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 ();
            //  ...
            /
本文标题为:如何在可取消的 async/await 中处理 TransactionScope?
				
        
 
            
        - 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
 - 在 LINQ to SQL 中使用 contains() 2022-01-01
 - CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
 - 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
 - Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
 - 使用 rss + c# 2022-01-01
 - 在 C# 中异步处理项目队列 2022-01-01
 - C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
 - Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
 - 带问号的 nvarchar 列结果 2022-01-01
 
						
						
						
						
						