gpt4 book ai didi

c# - 在异步/等待代码中重新分配 Transaction.Current 时上下文丢失

转载 作者:行者123 更新时间:2023-11-30 12:38:07 25 4
gpt4 key购买 nike

重新分配 Transaction.Current 时,我似乎失去了 TransactionScope 的原始 TransactionScopeAsyncFlowOption 行为。第二个 await 之后的代码失去了它的 Transaction.Current 值。

示例代码(Linqpad):

async Task Main()
{
Thread.CurrentThread.ManagedThreadId.Dump("before await");
var scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);
var transaction = Transaction.Current;

await Task.Delay(1000).ConfigureAwait(false);

Thread.CurrentThread.ManagedThreadId.Dump("after first await");
Transaction.Current = transaction;
Transaction.Current.Dump(); // not null

await Task.Delay(1000).ConfigureAwait(false);

Thread.CurrentThread.ManagedThreadId.Dump("after second await");
Transaction.Current.Dump(); // is null :/
}

know我应该在 TransactionScope 上使用 using 语句,而不是重新分配环境事务,但是由于某些原因,不可能这样做。我很好奇上面代码片段的行为原因,想知道是否有办法保持原始的 TransactionScopeAsyncFlowOption 行为。

最佳答案

我通过将 Transaction 对象包装在另一个启用了 TransactionScopeAsyncFlowOptionTransactionScope 中设法解决了这个问题:

async Task Main()
{
var scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);
var transaction = Transaction.Current;

await Task.Delay(1000);

Transaction.Current = transaction;
Debug.Assert(Transaction.Current != null); // not null

await Task.Delay(1000);

Debug.Assert(Transaction.Current == null); // is null :/

using (var innerScope = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled))
{
// Transaction.Current state is kept across async continuations
Debug.Assert(Transaction.Current != null); // not null
await Task.Delay(10);
Debug.Assert(Transaction.Current != null); // not null
innerScope.Complete();
}
}

关于c# - 在异步/等待代码中重新分配 Transaction.Current 时上下文丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55955218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com