我试图用System.Threading.Timer替换Thread.Sleep,我试图在下面的代码中实现它。更改的主要原因是,即使它在本地测试时有效,但它在服务器中无法正常工作。另外,我已经读过在这里使用它是不好的做法。
我已经看过几个例子(包括下面的例子),但我不确定如何在我的案例中使用它: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;
}
答案 0 :(得分:1)
想法是设置计时器,并在想要设置程序中的延迟时启用它:
System.Timers.Timer Delay = new System.Timers.Timer();
Delay.Elapsed += new System.Timers.ElapsedEventHandler(Delay_Elapsed);
Delay.Interval=Convert.ToInt32(milliseconds);
Delay.Enabled = false;
void Delay_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Delay.Enabled = false;
}
......
.....
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());
Delay.Enabled = true;
while (Delay.Enabled)
{
////Wait until time passes
}
Console.WriteLine("Download files after sleep of: " + nextTimeRead.ToString());
DownloadFilesByPeriod(nextTimeRead);
}