C#如何在给定时间运行代码?

use*_*360 0 c#

简而言之,

我早上开始运行我的C#程序,程序应该在下午5:45向用户显示一条消息.我怎么能在C#中做到这一点?

编辑:我问过这个问题因为我认为使用计时器不是最好的解决方案(定期比较当前时间和运行任务所需的时间):

private void timerDoWork_Tick(object sender, EventArgs e)
{
    if (DateTime.Now >= _timeToDoWork)
    {

        MessageBox.Show("Time to go home!");
        timerDoWork.Enabled = false;

    }
}
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 5

我问过这个问题因为我认为使用计时器不是最好的解决方案(定期比较当前时间和运行任务所需的时间)

为什么?为什么不定时最佳解决方案?IMO计时器是最佳解决方案.但不是你实施的方式.请尝试以下方法.

private System.Threading.Timer timer;
private void SetUpTimer(TimeSpan alertTime)
{
     DateTime current = DateTime.Now;
     TimeSpan timeToGo = alertTime - current.TimeOfDay;
     if (timeToGo < TimeSpan.Zero)
     {
        return;//time already passed
     }
     this.timer = new System.Threading.Timer(x =>
     {
         this.ShowMessageToUser();
     }, null, timeToGo, Timeout.InfiniteTimeSpan);
}

private void ShowMessageToUser()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new MethodInvoker(this.ShowMessageToUser));
    }
    else
    {
        MessageBox.Show("Your message");
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它

 SetUpTimer(new TimeSpan(17, 45, 00));
Run Code Online (Sandbox Code Playgroud)