Delayed function calls

后端 未结 12 1305
星月不相逢
星月不相逢 2020-11-30 22:07

Is there a nice simple method of delaying a function call whilst letting the thread continue executing?

e.g.

public void foo()
{
    // Do stuff!

           


        
12条回答
  •  旧巷少年郎
    2020-11-30 22:22

    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));
    }
    

提交回复
热议问题