Skip to content

Instantly share code, notes, and snippets.

@DeoEsor
Created June 7, 2022 15:31
Show Gist options
  • Save DeoEsor/a9fe49d55b66810b3386196a968540a7 to your computer and use it in GitHub Desktop.
Save DeoEsor/a9fe49d55b66810b3386196a968540a7 to your computer and use it in GitHub Desktop.
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;
return _completedOk;
}
public async Task SomeMethod(CancellationToken token)
{
var beginInvoke = Handler.BeginInvoke(null, EventArgs.Empty, null, null);
while (beginInvoke.IsCompleted)
{
if (!token.IsCancellationRequested)
Thread.Sleep(50);
return;
}
}
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