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

前端 未结 12 1455
我在风中等你
我在风中等你 2020-12-13 08:54

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

12条回答
  •  盖世英雄少女心
    2020-12-13 09:24

    treze's code is working just fine. This might help the ones who have to use older .NET versions:

    private static volatile List _timers = new List();
    private static object lockobj = new object();
    public static void SetTimeout(Action action, int delayInMilliseconds)
    {
        System.Threading.Timer timer = null;
        var cb = new System.Threading.TimerCallback((state) =>
        {
            lock (lockobj)
                _timers.Remove(timer);
            timer.Dispose();
            action();
        });
        lock (lockobj)
            _timers.Add(timer = new System.Threading.Timer(cb, null, delayInMilliseconds, System.Threading.Timeout.Infinite));
    }
    

提交回复
热议问题