Skip to content

Instantly share code, notes, and snippets.

@Flayed
Created September 15, 2017 02:39
Show Gist options
  • Select an option

  • Save Flayed/5bc1d83b4419386cfc9c8c90154f4ac3 to your computer and use it in GitHub Desktop.

Select an option

Save Flayed/5bc1d83b4419386cfc9c8c90154f4ac3 to your computer and use it in GitHub Desktop.
Starts a task, deferring the action until a timeout has elapsed
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