Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-3997

ServerMonitor captures execution context for background tasks

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      Summary

      When `ServerMonitor` calls `_roundTripTimeMonitor.RunAsync()`, it does not suppress the execution context flow. Because of that, any value present in the execution context when the connection to the server is initialized (= usually when the first instance of `MongoClient` is created) will be captured and kept alive forever by the RoundTripMonitor.

       

      The behavior was observed in 2.13.2, but still present in current version.

       

      How to Reproduce

      ```

      public class Program
      {
          private static AsyncLocal<object[]> asyncLocal = new();

          public static async Task Main(string[] args)
         

      {         Console.WriteLine(TestExecutionContextCapture(InitializeClient));         Console.WriteLine(TestExecutionContextCapture(Baseline));     }

          private static bool TestExecutionContextCapture(Action action)
         

      {         var reference = AllocateAndAssignPayload();         Task.Run(action).Wait();         asyncLocal.Value = null;         GC.Collect(2, GCCollectionMode.Forced, blocking: true);         GC.WaitForPendingFinalizers();         GC.Collect(2, GCCollectionMode.Forced, blocking: true);         return reference.IsAlive;     }

          private static WeakReference AllocateAndAssignPayload()
         

      {         var payload = new object[1024 * 1024];         asyncLocal.Value = payload;         return new WeakReference(payload);     }

      }

      ```

       

       

       

            Assignee:
            Unassigned Unassigned
            Reporter:
            krix33@gmail.com Kevin Gosse
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: