namespace RemoteExec.Client;
///
/// An async-compatible manual reset event that can be awaited.
///
internal class AsyncManualResetEvent
{
private volatile TaskCompletionSource _tcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
///
/// Initializes a new instance of the class.
///
/// If true, the event is initially signaled.
public AsyncManualResetEvent(bool initialState)
{
if (initialState)
{
_ = _tcs.TrySetResult(true);
}
}
///
/// Asynchronously waits for the event to be signaled.
///
/// A cancellation token to cancel the wait operation.
/// A task that completes when the event is signaled.
public Task WaitAsync(CancellationToken ct)
{
return _tcs.Task.WaitAsync(ct);
}
///
/// Sets the event to a signaled state, releasing all waiting tasks.
///
public void Set()
{
_ = _tcs.TrySetResult(true);
}
///
/// Resets the event to an unsignaled state.
///
public void Reset()
{
while (true)
{
TaskCompletionSource tcs = _tcs;
if (!tcs.Task.IsCompleted ||
Interlocked.CompareExchange(ref _tcs, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), tcs) == tcs)
{
return;
}
}
}
}