Skip to content

Instantly share code, notes, and snippets.

@DeoEsor
Last active June 7, 2022 22:50
Show Gist options
  • Save DeoEsor/f1a43d4361d5f34e2cb6fcc5aaeb7338 to your computer and use it in GitHub Desktop.
Save DeoEsor/f1a43d4361d5f34e2cb6fcc5aaeb7338 to your computer and use it in GitHub Desktop.
using System.Timers;
public class AsyncCaller : IAsyncDisposable
{
private System.Timers.Timer _timer;
private readonly CancellationTokenSource _tokenSource;
private readonly EventHandler _handler;
private bool _completedOk;
public AsyncCaller(EventHandler h)
{
_tokenSource = new CancellationTokenSource();
_handler = h;
_timer = null!;
_tokenSource.Token.Register(() => _completedOk = false);
}
private void OnTimedEvent(object? sender, ElapsedEventArgs e) => _tokenSource.Cancel();
public bool Invoke(int milliseconds, object? sender, EventArgs eventArgs)
{
_completedOk = false;
_timer = new System.Timers.Timer(milliseconds);
_timer.Elapsed += OnTimedEvent;
_timer.Enabled = true;
var asyncResult = _handler.BeginInvoke(null, EventArgs.Empty, null, null);
while (asyncResult.IsCompleted)
{
if (_tokenSource.Token.IsCancellationRequested) return false;
Thread.Sleep(50);
}
_handler.EndInvoke(asyncResult);
_completedOk = true;
return _completedOk;
}
public async ValueTask DisposeAsync()
{
_timer.Dispose();
_tokenSource.Dispose();
GC.SuppressFinalize(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment