gpt4 book ai didi

c# - 无法匹配 C# 中的时间

转载 作者:太空宇宙 更新时间:2023-11-03 17:45:09 25 4
gpt4 key购买 nike

我有一个用 C# 编写的非常简单的程序,但循环永远不会退出,因为时间不匹配。

static void Main(string[] args)
{
while (System.DateTime.Now != new System.DateTime(2011, 05, 23, 22, 17, 0))
{
}
System.Diagnostics.Process.Start(file);
}

这个想法是,当时间滴答到指定时间时,将启动给定文件。但是,我已经使用例如比 Windows 报告的当前时间提前一分钟的值测试了这个程序,并且它不会启动该过程。我已验证 Process.Start调用是正确的。有什么建议?

编辑:不,这不是一个实验或任何类似的东西。这是因为我一直在 sleep 时关掉闹钟。 file是一个 mp3 文件,我将打开我的扬声器,我很确定我没有能力在我的 sleep 中处理它。我用程序解决的第一个实际问题。由于它具有相当特定的目的,我认为您会同意另一种解决方案的必要性是有限的。

编辑:我没有意识到 DateTime 类型下降到那种精度,否则我自己会发现这一点。我认为它们只在秒内有效,并且由于循环即使在 IDE 中的 Debug模式下也应该每秒运行很多次,所以我不明白为什么完全匹配是不合理的。但是,当然,如果你将它与一百纳秒进行比较,那是非常不可能的。

最佳答案

你应该做

static void Main(string[] args)
{
while (System.DateTime.Now < new System.DateTime(2011, 05, 23, 22, 17, 0))
{
}
System.Diagnostics.Process.Start(file);
}

因为如果你不勾选那个确切的时间,它就不会退出这个时间

编辑 详细解释为什么 != 很可能不起作用
所以实际上你可以这样写代码:
static void Main(string[] args)
{
DateTime fireDate = new DateTime(2011, 05, 23, 22, 17, 0);

while (System.DateTime.Now < fireDate)
{
}
System.Diagnostics.Process.Start(file);
}

正如 Ben Voigt 指出的 DateTime比较看 Ticks DateTime 上的属性(property) DateTime.Ticks这是 1/10,000一毫秒。

您的循环可能不会那么频繁地执行。

关于c# - 无法匹配 C# 中的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6103200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com