我如何在c#中等待一段时间(windows服务)
本文关键字:一段时间 windows 服务 等待 | 更新日期: 2023-09-27 18:03:23
我在c#上创建了windows服务。现在我有扫描DB的方法。我需要每分钟调用这个方法两次。其实我不知道如何在windows服务中等待。我试过Thread.Sleep…但是什么也没发生。请帮我解决这个问题。
private int wait;
protected void Start()
{
wait = 1000;
while (true)
{
if (wait < 30000)
wait += wait;
//implement logic for waiting
Video video = new Video();
video.FindFileForConvert();
if (video.Path != null)
{
Console.WriteLine("video != null. video path = {0}", video.Path);
video.BeginConvertation();
video.DeleteOriginFile();
wait = 1000;
}
}
}
您应该使用System.Threading.Timer。因为Thread.sleep
至少在某些情况下不是一个好的实践
可以使用Timer
public static int Main() {
/* Adds the event and the event handler for the method that will
process the timer event to the timer. */
myTimer.Tick += new EventHandler(TimerEventProcessor);
// Sets the timer interval to 5 seconds.
myTimer.Interval = 5000;
myTimer.Start();
// Runs the timer, and raises the event.
while(exitFlag == false) {
// Processes all the events in the queue.
Application.DoEvents();
}
return 0;
}
我可能弄错了,但我认为这段代码将帮助您解决您的问题。DispatcherTimer
DispatcherTimer dispathcerTimer = new DispatcherTimer();
dispathcerTimer.Interval = TimeSpan.FromMinutes(2);
dispathcerTimer.Tick += dispathcerTimer_Tick;
dispathcerTimer.Start();
void dispatcherTime_Tick(object sender, object e)
{
//function, which needs to be invoked every two minutes.
}