【问题标题】:Is LogicalOperationStack incompatible with async in .Net 4.5LogicalOperationStack 与 .Net 4.5 中的异步不兼容吗
【发布时间】:2015-04-30 10:12:51
【问题描述】:

Trace.CorrelationManager.LogicalOperationStack 支持嵌套逻辑操作标识符,其中最常见的情况是日志记录 (NDC)。它还应该与async-await 一起使用吗?

这是一个使用LogicalFlow 的简单示例,这是我对LogicalOperationStack 的简单包装:

private static void Main() => OuterOperationAsync().GetAwaiter().GetResult();

private static async Task OuterOperationAsync()
{
    Console.WriteLine(LogicalFlow.CurrentOperationId);
    using (LogicalFlow.StartScope())
    {
        Console.WriteLine("\t" + LogicalFlow.CurrentOperationId);
        await InnerOperationAsync();
        Console.WriteLine("\t" + LogicalFlow.CurrentOperationId);
        await InnerOperationAsync();
        Console.WriteLine("\t" + LogicalFlow.CurrentOperationId);
    }
    Console.WriteLine(LogicalFlow.CurrentOperationId);
}

private static async Task InnerOperationAsync()
{
    using (LogicalFlow.StartScope())
    {
        await Task.Delay(100);
    }
}

LogicalFlow:

public static class LogicalFlow
{
    public static Guid CurrentOperationId =>
        Trace.CorrelationManager.LogicalOperationStack.Count > 0
            ? (Guid) Trace.CorrelationManager.LogicalOperationStack.Peek()
            : Guid.Empty;

    public static IDisposable StartScope()
    {
        Trace.CorrelationManager.StartLogicalOperation();
        return new Stopper();
    }

    private static void StopScope() => 
        Trace.CorrelationManager.StopLogicalOperation();

    private class Stopper : IDisposable
    {
        private bool _isDisposed;
        public void Dispose()
        {
            if (!_isDisposed)
            {
                StopScope();
                _isDisposed = true;
            }
        }
    }
}

输出:

00000000-0000-0000-0000-000000000000
    49985135-1e39-404c-834a-9f12026d9b65
    54674452-e1c5-4b1b-91ed-6bd6ea725b98
    c6ec00fd-bff8-4bde-bf70-e073b6714ae5
54674452-e1c5-4b1b-91ed-6bd6ea725b98

具体的值并不重要,但据我了解,外线应显示Guid.Empty(即00000000-0000-0000-0000-000000000000),内线应显示相同的Guid值。

您可能会说LogicalOperationStack 使用了Stack,它不是线程安全的,这就是输出错误的原因。但是虽然这通常是正确的,但在这种情况下只有一个线程同时访问LogicalOperationStack(每个async 操作在调用时都会等待,并且不使用组合符,例如Task.WhenAll)

问题在于LogicalOperationStack 存储在具有写入时复制行为的CallContext 中。这意味着只要您没有在CallContext 中显式设置某些内容(并且当您使用StartLogicalOperation 添加到现有堆栈时也没有),您使用的是父上下文而不是您自己的上下文。

这可以通过在添加到现有堆栈之前简单地将 anything 设置到 CallContext 来显示。例如,如果我们将StartScope 更改为:

public static IDisposable StartScope()
{
    CallContext.LogicalSetData("Bar", "Arnon");
    Trace.CorrelationManager.StartLogicalOperation();
    return new Stopper();
}

输出是:

00000000-0000-0000-0000-000000000000
    fdc22318-53ef-4ae5-83ff-6c3e3864e37a
    fdc22318-53ef-4ae5-83ff-6c3e3864e37a
    fdc22318-53ef-4ae5-83ff-6c3e3864e37a
00000000-0000-0000-0000-000000000000

注意:我并不是建议任何人实际这样做。真正实用的解决方案是使用ImmutableStack 而不是LogicalOperationStack,因为它既是线程安全的,又因为当您调用Pop 时它是不可变的,您会得到一个新的ImmutableStack,然后您需要将其设置回CallContext。完整的实现可以作为这个问题的答案:Tracking c#/.NET tasks flow

那么,LogicalOperationStack 是否应该与 async 一起使用,而这只是一个错误? LogicalOperationStack 不适合 async 世界吗?还是我错过了什么?


更新:使用Task.Delay 显然令人困惑,因为它使用System.Threading.Timer 而captures the ExecutionContext internally。使用await Task.Yield(); 而不是await Task.Delay(100); 使示例更易于理解。

【问题讨论】:

  • @Noseratio 不。这不是关于async-await,而是关于一个已经修复的错误。
  • 同意,不是骗子。您是否检查过它是否在同一线程上按预期工作,例如如果您将await Task.Delay(100) 替换为Task.Delay(100).Wait()?
  • @downvoter 有什么问题吗?
  • 这是一个很棒的技术问题。也许,投反对票的人根本不明白这是怎么回事。

标签: c# .net async-await .net-4.5


【解决方案1】:

如果您仍然对此感兴趣,我认为这是它们的流动方式中的一个错误LogicalOperationStack,我认为报告它是个好主意。

他们对LogicalOperationStack 的堆栈here in LogicalCallContext.Clone 进行了特殊处理,方法是进行深拷贝(与通过CallContext.LogicalSetData/LogicalGetData 存储的其他数据不同,仅执行浅拷贝)。

每次调用ExecutionContext.CreateCopy 或ExecutionContext.CreateMutableCopy 时都会调用此LogicalCallContext.Clone 以流化ExecutionContext。

根据您的代码,我做了一个小实验,为LogicalCallContext 中的"System.Diagnostics.Trace.CorrelationManagerSlot" 插槽提供我自己的可变堆栈,以查看它实际被克隆的时间和次数。

代码:

using System;
using System.Collections;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static readonly string CorrelationManagerSlot = "System.Diagnostics.Trace.CorrelationManagerSlot";

        public static void ShowCorrelationManagerStack(object where)
        {
            object top = "null";
            var stack = (MyStack)CallContext.LogicalGetData(CorrelationManagerSlot);
            if (stack.Count > 0)
                top = stack.Peek();

            Console.WriteLine("{0}: MyStack Id={1}, Count={2}, on thread {3}, top: {4}",
                where, stack.Id, stack.Count, Environment.CurrentManagedThreadId, top);
        }

        private static void Main()
        {
            CallContext.LogicalSetData(CorrelationManagerSlot, new MyStack());

            OuterOperationAsync().Wait();
            Console.ReadLine();
        }

        private static async Task OuterOperationAsync()
        {
            ShowCorrelationManagerStack(1.1);

            using (LogicalFlow.StartScope())
            {
                ShowCorrelationManagerStack(1.2);
                Console.WriteLine("\t" + LogicalFlow.CurrentOperationId);
                await InnerOperationAsync();
                ShowCorrelationManagerStack(1.3);
                Console.WriteLine("\t" + LogicalFlow.CurrentOperationId);
                await InnerOperationAsync();
                ShowCorrelationManagerStack(1.4);
                Console.WriteLine("\t" + LogicalFlow.CurrentOperationId);
            }

            ShowCorrelationManagerStack(1.5);
        }

        private static async Task InnerOperationAsync()
        {
            ShowCorrelationManagerStack(2.1);
            using (LogicalFlow.StartScope())
            {
                ShowCorrelationManagerStack(2.2);
                await Task.Delay(100);
                ShowCorrelationManagerStack(2.3);
            }
            ShowCorrelationManagerStack(2.4);
        }
    }

    public class MyStack : Stack, ICloneable
    {
        public static int s_Id = 0;

        public int Id { get; private set; }

        object ICloneable.Clone()
        {
            var cloneId = Interlocked.Increment(ref s_Id); ;
            Console.WriteLine("Cloning MyStack Id={0} into {1} on thread {2}", this.Id, cloneId, Environment.CurrentManagedThreadId);

            var clone = new MyStack();
            clone.Id = cloneId;

            foreach (var item in this.ToArray().Reverse())
                clone.Push(item);

            return clone;
        }
    }

    public static class LogicalFlow
    {
        public static Guid CurrentOperationId
        {
            get
            {
                return Trace.CorrelationManager.LogicalOperationStack.Count > 0
                    ? (Guid)Trace.CorrelationManager.LogicalOperationStack.Peek()
                    : Guid.Empty;
            }
        }

        public static IDisposable StartScope()
        {
            Program.ShowCorrelationManagerStack("Before StartLogicalOperation");
            Trace.CorrelationManager.StartLogicalOperation();
            Program.ShowCorrelationManagerStack("After StartLogicalOperation");
            return new Stopper();
        }

        private static void StopScope()
        {
            Program.ShowCorrelationManagerStack("Before StopLogicalOperation");
            Trace.CorrelationManager.StopLogicalOperation();
            Program.ShowCorrelationManagerStack("After StopLogicalOperation");
        }

        private class Stopper : IDisposable
        {
            private bool _isDisposed;
            public void Dispose()
            {
                if (!_isDisposed)
                {
                    StopScope();
                    _isDisposed = true;
                }
            }
        }
    }
}

结果相当令人惊讶。即使这个异步工作流只涉及两个线程,堆栈也会被克隆多达 4 次。问题是,匹配的Stack.Push 和Stack.Pop 操作(由StartLogicalOperation/StopLogicalOperation 调用)对堆栈的不同的、不匹配的克隆进行操作,从而使“逻辑”堆栈失衡。这就是错误所在。

这确实使 LogicalOperationStack 在异步调用中完全无法使用,即使没有并发的任务分支。

更新,我还对同步调用的行为方式做了一些研究,以解决these comments:

同意,不是骗子。您是否检查过它是否按预期工作 线程,例如如果您将 await Task.Delay(100) 替换为 Task.Delay(100).Wait()? – Noseratio 2 月 27 日 21:00

@Noseratio 是的。它当然有效,因为只有一个线程(所以只有一个 CallContext)。好像方法没有 异步开始。 – i3arnon 2 月 27 日 21:01

单线程并不意味着单个CallContext。即使对于同一单线程上的同步延续,执行上下文(及其内部LogicalCallContext)也可以被克隆。例如,使用上面的代码:

private static void Main()
{
    CallContext.LogicalSetData(CorrelationManagerSlot, new MyStack());

    ShowCorrelationManagerStack(0.1);

    CallContext.LogicalSetData("slot1", "value1");
    Console.WriteLine(CallContext.LogicalGetData("slot1"));

    Task.FromResult(0).ContinueWith(t =>
        {
            ShowCorrelationManagerStack(0.2);

            CallContext.LogicalSetData("slot1", "value2");
            Console.WriteLine(CallContext.LogicalGetData("slot1"));
        }, 
        CancellationToken.None,
        TaskContinuationOptions.ExecuteSynchronously,
        TaskScheduler.Default);

    ShowCorrelationManagerStack(0.3);
    Console.WriteLine(CallContext.LogicalGetData("slot1"));

    // ...
}

输出(注意我们如何丢失"value2"):

0.1:MyStack Id=0,Count=0,在线程 9 上,顶部: 价值1 在线程 9 上将 MyStack Id=0 克隆为 1 0.2:MyStack Id=1,Count=0,在线程 9 上,顶部: 价值2 0.3:MyStack Id=0,Count=0,在线程 9 上,顶部: 价值1

【讨论】:

  • Task.Delay 在内部捕获ExecutionContext,因此您有 4 个克隆也就不足为奇了。您可以使用Task.Yield 使其更易于理解。使用Task.Yield,您只能获得预期的 2 个克隆。正如我所描述的,问题在于,由于“写时复制”行为,您在不应该使用父上下文时使用了父上下文。在您的示例中,它表现为 2 个克隆是从同一个原始堆栈中克隆的。
  • 关于您的更新:我没有声明堆栈不会被Task.Delay(100).Wait() 克隆(实际上,在这种情况下它确实会被克隆,但它不会被Task.Yield.GetAwaiter().GetResult() 克隆) .我已经声明它按预期工作,因为运行代码的单个线程不使用克隆的堆栈(就像你的 "value2")
  • 另外,您的MyStack.Clone 每次都反转堆栈时不会正确克隆堆栈。
  • @i3arnon,确实有一个可以修复为foreach (var item in this.ToArray().Reverse())的错误。我认为这不会改变Push/Pop 在此处对堆栈的不同克隆进行操作的主要思想。我稍后会验证。
  • 当然有,这是问题的前提。两种方法Push 到同一个堆栈,然后它被克隆两次(每个await 一次)。第一个 Pop 发生在内部方法中的第一个克隆(有 2 个项目)上,第二个发生在第二个克隆上,它也有 2 个项目(尽管它应该只有一个)。发生这种情况是因为内部方法添加到外部方法的堆栈中,因为写入时复制没有副本。
【解决方案2】:

是的,LogicalOperationStack 应该与 async-await 一起工作,而 这是一个它不兼容的错误。

我已经联系了微软的相关开发人员,他的回复是这样的:

"我不知道这一点,但它似乎确实坏了。写时复制逻辑的行为应该与我们真正创建了 @987654326 的副本完全相同@ 进入方法。但是,复制 ExecutionContext 将创建 CorrelationManager 上下文的深层副本,因为它在 CallContext.Clone() 中是特殊情况。我们在复制时不考虑这一点-写逻辑。”

此外,他建议使用 .Net 4.6 中添加的新 System.Threading.AsyncLocal<T> 类,它应该可以正确处理该问题。

所以,我继续使用 VS2015 RC 和 .Net 4.6 在 AsyncLocal 之上实现 LogicalFlow 而不是 LogicalOperationStack:

public static class LogicalFlow
{
    private static AsyncLocal<Stack> _asyncLogicalOperationStack = new AsyncLocal<Stack>();

    private static Stack AsyncLogicalOperationStack
    {
        get
        {
            if (_asyncLogicalOperationStack.Value == null)
            {
                _asyncLogicalOperationStack.Value = new Stack();
            }

            return _asyncLogicalOperationStack.Value;
        }
    }

    public static Guid CurrentOperationId =>
        AsyncLogicalOperationStack.Count > 0
            ? (Guid)AsyncLogicalOperationStack.Peek()
            : Guid.Empty;

    public static IDisposable StartScope()
    {
        AsyncLogicalOperationStack.Push(Guid.NewGuid());
        return new Stopper();
    }

    private static void StopScope() =>
        AsyncLogicalOperationStack.Pop();
}

同样测试的输出确实是应该的:

00000000-0000-0000-0000-000000000000
    ae90c3e3-c801-4bc8-bc34-9bccfc2b692a
    ae90c3e3-c801-4bc8-bc34-9bccfc2b692a
    ae90c3e3-c801-4bc8-bc34-9bccfc2b692a
00000000-0000-0000-0000-000000000000

【讨论】:

  • 我很好奇,您是如何联系微软的相关开发人员的? The bug at Connect 尚未收到 Microsoft 的任何反馈。
  • 有什么方法可以在 .net 4.5 中实现 AsyncLocal 行为吗?
  • @taras.roshko true,因为我创建了一次 AsyncLocal 并在需要为每个异步流分别设置它时设置它的值一次。我相应地更新了答案
  • @i3arnon 您的LogicalFlow 类在子操作中启动多个并行任务并创建自己的子操作的情况下是否会正常运行?换句话说,这个类线程安全吗?
  • 我认为这个解决方案不够好。就像您在下面的评论中所说的那样,需要深度克隆,否则几个线程最终会得到相同的(非线程安全堆栈)。如果我执行using (LogicalFlow.StartScope()) { Task.WaitAll(Task.Run(InnerOperationAsync), Task.Run(InnerOperationAsync)) } 之类的操作,所有 3 个线程(父线程和两个子线程)都将具有相同的 Stack 实例(正如我使用 Object.ReferenceEquals 验证的那样)。但是,您在这里所做的应该可以正常工作,因为它利用了深度复制:stackoverflow.com/a/24468972/67824。
【解决方案3】:

这里和网络上提到的解决方案之一是在上下文中调用 LogicalSetData:

CallContext.LogicalSetData("one", null);
Trace.CorrelationManager.StartLogicalOperation();

但实际上,仅仅读取当前的执行上下文就足够了:

var context = Thread.CurrentThread.ExecutionContext;
Trace.CorrelationManager.StartLogicalOperation();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多