稍后执行函数

Executing a function at a later time

我有以下代码,其目的是在特定时间调用函数。但是,当调用 WaitTask.Start(); Additional information: Start may not be called on a promise-style task.

时出现异常
DateTime today = DateTime.Today;
DateTime twoThirtyET = today.AddHours(14.50);

Execute(CallAtTime, twoThirtyET);

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

private void CallAtTime()
{
    Console.WriteLine("Called at time");
}

您可以使用计时器。 (2000 是以毫秒为单位的间隔,所以 2 秒)

class Program
{
    private static System.Timers.Timer _timer;
    static void Main(string[] args)
    {
        _timer = new System.Timers.Timer(2000);
        _timer.Elapsed += timer_Elapsed;
        _timer.Start();
        Console.ReadLine();
    }

    static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        _timer.Stop(); //If you only want it to run once
        Console.WriteLine("Elapsed");
    }
}

您正在获取 Additional information: Start may not be called on a promise-style task.,因为 Task.Delay 中的 Task 已经开始,查看 this answer 了解更多信息。

最简单的更改是删除对 WaitTask.StartNew() 的调用,因为它是不必要的。

哦,您可能想在回调中实际调用您的操作,而不是仅仅返回它:

WaitTask.ContinueWith(_ => action());

完整示例

namespace YourNamespace
{
    using System.Threading;

    public class MainClass
    {
        public void Main()
        {
            PostponedAction action = new PostponedAction();
            action.WaitExecute(DateTime.Today.AddHours(14.5) - DateTime.Now);
        }
    }

    public class PostponedAction
    {
        public void WaitExecute(TimeSpan waitTime)
        {
            Thread.Sleep(waitTime);
            // Do stuff
        }
    }
}