Created
September 15, 2017 02:39
-
-
Save Flayed/5bc1d83b4419386cfc9c8c90154f4ac3 to your computer and use it in GitHub Desktop.
Starts a task, deferring the action until a timeout has elapsed
This file contains hidden or 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
| private readonly ConcurrentDictionary<Guid, Task> _tasks = new ConcurrentDictionary<Guid, Task>(); | |
| public void Defer(Action action, int delay, CancellationToken cancellationToken) | |
| { | |
| if (action == null) return; | |
| if (cancellationToken.IsCancellationRequested) return; | |
| Guid key = Guid.NewGuid(); | |
| _tasks.TryAdd(key, Task.Run(async () => | |
| { | |
| try | |
| { | |
| if (delay > 0) | |
| { | |
| await Task.Delay(delay, cancellationToken).ConfigureAwait(false); | |
| } | |
| if (cancellationToken.IsCancellationRequested) | |
| return; | |
| action.Invoke(); | |
| } | |
| catch (OperationCanceledException) | |
| { | |
| return; | |
| } | |
| catch (Exception) | |
| { | |
| throw; | |
| } | |
| finally | |
| { | |
| RemoveTask(key); | |
| } | |
| }, cancellationToken)); | |
| } | |
| private void RemoveTask(Guid key) | |
| { | |
| Task t; | |
| _tasks.TryRemove(key, out t); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment