Как мога да изчакам известно време в c# (услуга на Windows)

Създадох услуга на Windows на C#. Засега имам методи за сканиране на БД. Трябва да извикам този метод два пъти в минута. Всъщност не знам метода за изчакване в услугата на 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;
        }
    }
}

person Viktor Ischenko    schedule 12.03.2013    source източник
comment
Използвайте Timer и си вършете работата при събития с таймер.   -  person Hamlet Hakobyan    schedule 12.03.2013
comment
какъв е интервалът, използван в Thread.Sleep()?   -  person Cris    schedule 12.03.2013


Отговори (3)


Можете да използвате Таймер

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;
}
person dotmido    schedule 12.03.2013

Трябва да използвате System.Threading.Timer за същото . Тъй като Thread.sleep не е добра практика поне в някои случаи.

person Community    schedule 12.03.2013
comment
Бихте ли разяснили по-подробно разликата между System.Threading.Timer и System.Threading.Thread.Sleep? Любопитен съм да разбера защо едното е по-добра практика от другото. - person Nolonar; 12.03.2013
comment
@Nolonar ТАКА и това msdn връзка - person ; 12.03.2013

Може да греша, но мисля, че този код ще ви помогне да разрешите проблема си. 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.     
}
person Viacheslav    schedule 12.03.2013
comment
Мисля, че DispatcherTimer би бил по-подходящ за задачи, свързани с потребителския интерфейс. - person D.Rosado; 12.03.2013