Skip to content

System.Diagnostics.CorrelationManager is not thread-safe #50480

Description

@mahalex

Description

The following code crashes due to issue in System.Diagnostics.CorrelationManager, which appears to be not thread-safe (even though it uses an AsyncLocalStackWrapper).

using System.Diagnostics;
using System.Threading;

namespace CorrelationManagerExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var t1 = new Thread(Method);
            var t2 = new Thread(Method);
            t1.Start();
            t2.Start();
        }

        private static void Method()
        {
            Trace.CorrelationManager.StartLogicalOperation();
            Trace.CorrelationManager.StopLogicalOperation();
        }
    }
}

Configuration

I verified by compiling and running this code using .NET SDK 5.0.201 on Windows 10 (x64).

Regression?

A similar issue was reported in 2005 against the .NET Framework implementation, and was apparently fixed then.
So recent versions of .NET Framework do not have this issue (I verified this by re-targeting the project to net461).

Other information

Stack trace:

Unhandled exception. System.InvalidOperationException: Stack empty.
   at System.Collections.Stack.Pop()
   at System.Diagnostics.CorrelationManager.AsyncLocalStackWrapper.Pop()
   at System.Diagnostics.CorrelationManager.StopLogicalOperation()
   at CorrelationManagerExample.Program.Method() in C:\git\CorrelationManagerExample\CorrelationManagerExample\Program.cs:line 19
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions