Delayed function calls

后端 未结 12 1309
星月不相逢
星月不相逢 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:41

    This will work either on older versions of .NET
    Cons: will execute in its own thread

    class CancelableDelay
        {
            Thread delayTh;
            Action action;
            int ms;
    
            public static CancelableDelay StartAfter(int milliseconds, Action action)
            {
                CancelableDelay result = new CancelableDelay() { ms = milliseconds };
                result.action = action;
                result.delayTh = new Thread(result.Delay);
                result.delayTh.Start();
                return result;
            }
    
            private CancelableDelay() { }
    
            void Delay()
            {
                try
                {
                    Thread.Sleep(ms);
                    action.Invoke();
                }
                catch (ThreadAbortException)
                { }
            }
    
            public void Cancel() => delayTh.Abort();
    
        }
    

    Usage:

    var job = CancelableDelay.StartAfter(1000, () => { WorkAfter1sec(); });  
    job.Cancel(); //to cancel the delayed job
    

提交回复
热议问题