[CSHARP-3997] ServerMonitor captures execution context for background tasks Created: 14/Dec/21  Updated: 14/Dec/21  Resolved: 14/Dec/21

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Unknown
Reporter: Kevin Gosse Assignee: Unassigned
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates CSHARP-3813 Suppress execution context flow when ... Closed

 Description   

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);     }

}

```

 

 

 



 Comments   
Comment by Dmitry Lukyanov (Inactive) [ 14/Dec/21 ]

Hello krix33@gmail.com, thanks for your report.

We know about this issue and track it in CSHARP-3813, please follow this ticket for updates.

Generated at Wed Feb 07 21:46:53 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.