@@ -20,7 +20,7 @@ internal class DiagnosticPortSession
20
20
private readonly bool _sampler ;
21
21
private readonly string _baseName ;
22
22
private readonly Task _connectTask ;
23
- private readonly object _sessionLock = new ( ) ;
23
+ private readonly SemaphoreSlim _semaphoreSlim ;
24
24
private Task ? _profilingTask ;
25
25
private readonly CancellationTokenSource _cancelConnectSource ;
26
26
private DiagnosticsClient ? _diagnosticsClient ;
@@ -36,6 +36,7 @@ public DiagnosticPortSession(int pid, bool sampler, string baseName, Cancellatio
36
36
_sampler = sampler ;
37
37
_baseName = baseName ;
38
38
_cancelConnectSource = new CancellationTokenSource ( ) ;
39
+ _semaphoreSlim = new SemaphoreSlim ( 0 ) ;
39
40
_connectTask = ConnectAndStartProfilingImpl ( pid , sampler , baseName , token ) ;
40
41
}
41
42
@@ -74,10 +75,11 @@ private async Task ConnectAndStartProfilingImpl(int pid, bool sampler, string ba
74
75
}
75
76
}
76
77
77
- public void StartProfiling ( CancellationToken token )
78
+ public async Task StartProfiling ( CancellationToken token )
78
79
{
79
80
// We want to make sure that we are not disposing while we are connecting
80
- Monitor . Enter ( _sessionLock ) ;
81
+ await _semaphoreSlim . WaitAsync ( token ) ;
82
+
81
83
try
82
84
{
83
85
if ( _disposed )
@@ -88,6 +90,7 @@ public void StartProfiling(CancellationToken token)
88
90
_profilingTask = _connectTask . ContinueWith ( async task =>
89
91
{
90
92
93
+
91
94
_nettraceFilePath = Path . Combine ( Environment . CurrentDirectory , $ "{ _baseName } _{ ( _sampler ? "sampler" : "main" ) } _{ _pid } .nettrace") ;
92
95
_nettraceFileStream = new FileStream ( _nettraceFilePath , FileMode . Create , FileAccess . Write , FileShare . Read , 65536 , FileOptions . Asynchronous ) ;
93
96
@@ -121,7 +124,7 @@ public void StartProfiling(CancellationToken token)
121
124
}
122
125
finally
123
126
{
124
- Monitor . Exit ( _sessionLock ) ;
127
+ _semaphoreSlim . Release ( ) ;
125
128
}
126
129
}
127
130
@@ -171,7 +174,9 @@ public async Task WaitForConnectAndStartSession()
171
174
172
175
public async ValueTask StopAndDisposeAsync ( )
173
176
{
174
- Monitor . Enter ( _sessionLock ) ;
177
+ // We want to make sure that we are not disposing while we are connecting
178
+ await _semaphoreSlim . WaitAsync ( CancellationToken . None ) ;
179
+
175
180
try
176
181
{
177
182
if ( _profilingTask is null )
@@ -236,7 +241,7 @@ public async ValueTask StopAndDisposeAsync()
236
241
finally
237
242
{
238
243
_disposed = true ;
239
- Monitor . Exit ( _sessionLock ) ;
244
+ _semaphoreSlim . Release ( ) ;
240
245
241
246
_cancelConnectSource . Dispose ( ) ;
242
247
}
0 commit comments