virtualx-engine/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/SemaphoreExtensions.cs
Raul Santos 71df6d66ae
Add readonly to C# methods and types that don't mutate
Also removes a few unnecessary temp variables
2022-11-14 20:32:20 +01:00

32 lines
1.2 KiB
C#

using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace GodotTools.IdeMessaging.Utils
{
public static class SemaphoreExtensions
{
public static ConfiguredTaskAwaitable<IDisposable> UseAsync(this SemaphoreSlim semaphoreSlim, CancellationToken cancellationToken = default(CancellationToken))
{
var wrapper = new SemaphoreSlimWaitReleaseWrapper(semaphoreSlim, out Task waitAsyncTask, cancellationToken);
return waitAsyncTask.ContinueWith<IDisposable>(t => wrapper, cancellationToken).ConfigureAwait(false);
}
private readonly struct SemaphoreSlimWaitReleaseWrapper : IDisposable
{
private readonly SemaphoreSlim semaphoreSlim;
public SemaphoreSlimWaitReleaseWrapper(SemaphoreSlim semaphoreSlim, out Task waitAsyncTask, CancellationToken cancellationToken = default(CancellationToken))
{
this.semaphoreSlim = semaphoreSlim;
waitAsyncTask = this.semaphoreSlim.WaitAsync(cancellationToken);
}
public void Dispose()
{
semaphoreSlim.Release();
}
}
}
}