【发布时间】:2014-11-03 00:22:18
【问题描述】:
我正在尝试将 Thread.Sleep 替换为 System.Threading.Timer,并尝试在以下代码中实现它。更改的主要原因是,即使它在本地测试时可以正常工作,但在服务器中却无法正常工作。另外,我读到在这里使用它是不好的做法。
我看过几个例子(包括下面的一个),但我不确定如何在我的案例中使用它:System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second
在我的控制台应用程序中,我需要每 15 分钟将文件复制到我们的服务器。所以在 :20, :35, :50, :05,我开始阅读那个季度的文件。在以下情况下,文件将在 :45 可用,我添加 5 分钟以防万一。
这是我的代码。我之前曾尝试并行复制几个季度的文件,但源文件所在的服务器遇到了问题。所以我要回到这个。
我的问题是,在这个例子中如何用 System.Threading.Timer 替换 Thread.Sleep?
我想试试await Task.Delay(Int32),但是我有VS2010:
DateTime lastTimeRead = new DateTime(2014, 9, 9, 8, 35, 0); //Last read at 8:35AM
DateTime nextTimeRead;
for (; ; )
{
now = DateTime.Now; //It's currently 8:43AM
nextTimeRead = LastTimeRead.AddMinutes(15); // nextTimeRead = 8:50AM.
if (nextTimeRead > now) //Yes, so wait 7 minutes for files to be available
{
TimeSpan span = nextTimeRead.Subtract(now);
Double milliseconds = span.TotalMilliseconds;
Console.WriteLine("Sleep for milliseconds: " + milliseconds.ToString());
Thread.Sleep(Convert.ToInt32(milliseconds));
Console.WriteLine("Download files after sleep of: " + nextTimeRead.ToString());
DownloadFilesByPeriod(nextTimeRead);
}
else // Files are available. Read.
{
Console.WriteLine("Download files no sleep: " + nextTimeRead.ToString());
DownloadFilesByPeriod(nextTimeRead);
}
LastTimeRead = nextTimeRead;
}
【问题讨论】:
-
Windows 有一个
Task Scheduler,如果你的模式真的那么简单,也许更容易担心你的程序内部逻辑并将开始留给 Windows。这已经过良好的测试和工作。 -
当您发布使用
Thread.Sleep的代码时,尚不清楚您在使用计时器时遇到了什么问题。您在使用每 15 分钟触发一次并从适当的起点开始的计时器时遇到了什么问题? -
你在问从哪里下载“VS Express 2013 for desktop”?
-
你能不能让我知道我需要改变什么才能使它成为一个好问题?
-
vmgmail - 我认为@DanielKelley 的评论非常清楚...您说您对基于
Timer的代码有问题,但示例没有显示任何痕迹...
标签: c# .net visual-studio-2010