获取 TransactionScope 以使用 async/await [英] Get TransactionScope to work with async / await
问题描述
我正在尝试将 async
/await
集成到我们的服务总线中.我基于这个例子实现了一个 SingleThreadSynchronizationContext
http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx.
I'm trying to integrate async
/await
into our service bus.
I implemented a SingleThreadSynchronizationContext
based on this example http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx.
它工作正常,除了一件事:TransactionScope
.我等待 TransactionScope
里面的东西,它打破了 TransactionScope
.
And it works fine, except for one thing: TransactionScope
. I await for stuff inside the TransactionScope
and it breaks the TransactionScope
.
TransactionScope
似乎不适合 async
/await
,当然是因为它使用 ThreadStaticAttribute 在线程中存储东西代码>.我收到此异常:
TransactionScope
doesn't seem to play nice with async
/await
, certainly because it stores things in the thread using ThreadStaticAttribute
. I get this exception:
TransactionScope 嵌套不正确.".
"TransactionScope nested incorrectly.".
我尝试在排队任务之前保存 TransactionScope
数据并在运行它之前恢复它,但它似乎没有改变任何事情.而且 TransactionScope
代码一团糟,所以很难理解那里发生了什么.
I tried to save TransactionScope
data before queuing the task and restore it before running it, but it doesn't seem to change a thing. And TransactionScope
code is a mess, so it's really hard to understand what's going on there.
有没有办法让它工作?有没有 TransactionScope
的替代方案?
Is there a way to make it work? Is there some alternative to TransactionScope
?
推荐答案
在 .NET Framework 4.5.1 中,有一组 采用 TransactionScopeAsyncFlowOption
参数的 TransactionScope
的新构造函数.
In .NET Framework 4.5.1, there is a set of new constructors for TransactionScope
that take a TransactionScopeAsyncFlowOption
parameter.
根据 MSDN,它支持跨线程延续的事务流.
According to the MSDN, it enables transaction flow across thread continuations.
我的理解是,它旨在允许您编写这样的代码:
My understanding is that it is meant to allow you to write code like this:
// transaction scope
using (var scope = new TransactionScope(... ,
TransactionScopeAsyncFlowOption.Enabled))
{
// connection
using (var connection = new SqlConnection(_connectionString))
{
// open connection asynchronously
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = ...;
// run command asynchronously
using (var dataReader = await command.ExecuteReaderAsync())
{
while (dataReader.Read())
{
...
}
}
}
}
scope.Complete();
}
这篇关于获取 TransactionScope 以使用 async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!