Chuu Chuu - 1 month ago 8
C# Question

Best way to create a "run-once" time delayed function in C#

I am trying to create a function that takes in an Action and a Timeout, and executes the Action after the Timeout. The function is to be non-blocking. The function must be thread safe. I also really, really want to avoid Thread.Sleep().

So far, the best I can do is this:

long currentKey = 0;
ConcurrentDictionary<long, Timer> timers = new ConcurrentDictionary<long, Timer>();

protected void Execute(Action action, int timeout_ms)
{
long currentKey = Interlocked.Increment(ref currentKey);
Timer t = new Timer(
(key) =>
{
action();
Timer lTimer;
if(timers.TryRemove((long)key, out lTimer))
{
lTimer.Dispose();
}
}, currentKey, Timeout.Infinite, Timeout.Infinite
);

timers[currentKey] = t;
t.Change(timeout_ms, Timeout.Infinite);
}


The problem is that calling Dispose() from the callback itself cannot be good. I am unsure if it is safe to "fall off" the end, i.e. Timers are considered live while their lambdas are executing, but even if this is the case I'd rather dispose it properly.

The "fire once with a delay" seems like such a common problem that there should be an easy way to do this, probably some other library in System.Threading I am missing, but right now the only solution I can think of is modification of the above with a dedicated cleanup task running on an interval. Any advice?

Answer

I don't know which version of C# you are using. But I think you could accomplish this by using the Task library. It would then look something like that.

public class PauseAndExecuter
{
    public async void Execute(Action action, int timeoutInMilliseconds)
    {
        await Task.Delay(timeoutInMilliseconds);
        action();
    }
}