Skip to content

Commit 7d49266

Browse files
committed
Remove usage of lock with async/await
1 parent 9e7ee56 commit 7d49266

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/Ultra.Core/DiagnosticPortSession.cs

+11-6
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ internal class DiagnosticPortSession
2020
private readonly bool _sampler;
2121
private readonly string _baseName;
2222
private readonly Task _connectTask;
23-
private readonly object _sessionLock = new();
23+
private readonly SemaphoreSlim _semaphoreSlim;
2424
private Task? _profilingTask;
2525
private readonly CancellationTokenSource _cancelConnectSource;
2626
private DiagnosticsClient? _diagnosticsClient;
@@ -36,6 +36,7 @@ public DiagnosticPortSession(int pid, bool sampler, string baseName, Cancellatio
3636
_sampler = sampler;
3737
_baseName = baseName;
3838
_cancelConnectSource = new CancellationTokenSource();
39+
_semaphoreSlim = new SemaphoreSlim(0);
3940
_connectTask = ConnectAndStartProfilingImpl(pid, sampler, baseName, token);
4041
}
4142

@@ -74,10 +75,11 @@ private async Task ConnectAndStartProfilingImpl(int pid, bool sampler, string ba
7475
}
7576
}
7677

77-
public void StartProfiling(CancellationToken token)
78+
public async Task StartProfiling(CancellationToken token)
7879
{
7980
// We want to make sure that we are not disposing while we are connecting
80-
Monitor.Enter(_sessionLock);
81+
await _semaphoreSlim.WaitAsync(token);
82+
8183
try
8284
{
8385
if (_disposed)
@@ -88,6 +90,7 @@ public void StartProfiling(CancellationToken token)
8890
_profilingTask = _connectTask.ContinueWith(async task =>
8991
{
9092

93+
9194
_nettraceFilePath = Path.Combine(Environment.CurrentDirectory, $"{_baseName}_{(_sampler ? "sampler" : "main")}_{_pid}.nettrace");
9295
_nettraceFileStream = new FileStream(_nettraceFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, 65536, FileOptions.Asynchronous);
9396

@@ -121,7 +124,7 @@ public void StartProfiling(CancellationToken token)
121124
}
122125
finally
123126
{
124-
Monitor.Exit(_sessionLock);
127+
_semaphoreSlim.Release();
125128
}
126129
}
127130

@@ -171,7 +174,9 @@ public async Task WaitForConnectAndStartSession()
171174

172175
public async ValueTask StopAndDisposeAsync()
173176
{
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+
175180
try
176181
{
177182
if (_profilingTask is null)
@@ -236,7 +241,7 @@ public async ValueTask StopAndDisposeAsync()
236241
finally
237242
{
238243
_disposed = true;
239-
Monitor.Exit(_sessionLock);
244+
_semaphoreSlim.Release();
240245

241246
_cancelConnectSource.Dispose();
242247
}

0 commit comments

Comments
 (0)