Created
June 7, 2022 15:31
-
-
Save DeoEsor/a9fe49d55b66810b3386196a968540a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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