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

前端 未结 12 1443
我在风中等你
我在风中等你 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:25

    I use this method to schedule a task for a specific time:

    public void ScheduleExecute(Action action, DateTime ExecutionTime)
    {
        Task WaitTask = Task.Delay(ExecutionTime.Subtract(DateTime.Now));
        WaitTask.ContinueWith(() => action());
        WaitTask.Start();
    }
    

    It should be noted that this only works for about 24 days out because of int32 max value.

提交回复
热议问题