Make EventPipeSession stop on Dispose (#2259)
authorSung Yoon Whang <suwhang@microsoft.com>
Fri, 7 May 2021 21:54:42 +0000 (14:54 -0700)
committerGitHub <noreply@github.com>
Fri, 7 May 2021 21:54:42 +0000 (14:54 -0700)
* Make EventPipeSession stop on Dispose

* catch exceptions thrown from stop

src/Microsoft.Diagnostics.NETCore.Client/DiagnosticsClient/EventPipeSession.cs

index 0ca12f92a143bf5215e4d540481afcaecd02fdb8..9f82f794183f3a4acba71beeaf081f3da9983949 100644 (file)
@@ -16,7 +16,8 @@ namespace Microsoft.Diagnostics.NETCore.Client
         private int _circularBufferMB;
         private long _sessionId;
         private IpcEndpoint _endpoint;
-        private bool disposedValue = false; // To detect redundant calls
+        private bool _disposedValue = false; // To detect redundant calls
+        private bool _stopped = false; // To detect redundant calls
 
         internal EventPipeSession(IpcEndpoint endpoint, IEnumerable<EventPipeProvider> providers, bool requestRundown, int circularBufferMB)
         {
@@ -49,6 +50,16 @@ namespace Microsoft.Diagnostics.NETCore.Client
         public void Stop()
         {
             Debug.Assert(_sessionId > 0);
+            
+            // Do not issue another Stop command if it has already been issued for this session instance.
+            if (_stopped)
+            {
+                return;
+            }
+            else
+            {
+                _stopped = true;
+            }
 
             byte[] payload = BitConverter.GetBytes(_sessionId);
             IpcMessage response;
@@ -76,13 +87,23 @@ namespace Microsoft.Diagnostics.NETCore.Client
 
         protected virtual void Dispose(bool disposing)
         {
-            if (!disposedValue)
+            // If session being disposed hasn't been stopped, attempt to stop it first
+            if (!_stopped)
+            {
+                try
+                {
+                    Stop();
+                }
+                catch {} // swallow any exceptions that may be thrown from Stop.
+            }
+
+            if (!_disposedValue)
             {
                 if (disposing)
                 {
                     EventStream?.Dispose();
                 }
-                disposedValue = true;
+                _disposedValue = true;
             }
         }