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?
基础教程推荐
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- 创建属性设置器委托 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01