Miles
Miles

Reputation: 5726

Correct way to have an endless wait

So I have a program that has a list of timers. Each of the timers has a tick event and lets just say for example, i have 10 timers started (all are in the List).

What is the best way to sit forever (or until i tell it to stop)? Should I just have a while loop?

foreach(Timer t in _timers)
{
   t.Start();
}

while(true)
{
   Application.DoEvents();
   System.Threading.Thread.Sleep(5000);
}

I have a feeling that this isn't the best way...

-- Update Here's my entire program:

public static void Main()
{
  // set some properties and set up the timers

    foreach(Timer t in _timers)
    {
       t.Start();
    }

    while(true)
    {
       Application.DoEvents();
       System.Threading.Thread.Sleep(5000);
    }
}

Thats it. There is no UI, there's nothing else. If I don't have the while loop, then the program just finishes.

Upvotes: 0

Views: 541

Answers (4)

dss539
dss539

Reputation: 6947

Use an EventWaitHandle or array of EventWaitHandles to block thread execution by using the WaitOne() or WaitAll() methods.

http://msdn.microsoft.com/en-us/library/kad9xah9.aspx

So for example

ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne();

will wait for eternity.

edit

Since you're making a service, you might want to read this article.

Upvotes: 8

Marc Gravell
Marc Gravell

Reputation: 1063198

By the Application.DoEvents, I assume you are on a UI thread here. It is never a good idea to keep the UI thread active (even with DoEvents). Why not just start the timers and release control back to the message pump. When the events tick it'll pick up the events.

Why do you want to loop?


Re the update; which Timer are you using? If you use System.Timers.Timer (with the Elapsed event) then it isn't bound to the message-loop (it fires on a separate thread): you can just hang the main thread, perhaps waiting on some exit condition:

using System;
using System.Timers;
static class Program {
    static void Main() {
        using (Timer timer = new Timer()) {
            timer.Interval = 2000;
            timer.Elapsed += delegate {
                Console.Error.WriteLine("tick");
            };
            timer.Start();
            Console.WriteLine("Press [ret] to exit");
            Console.ReadLine();
            timer.Stop();
        }
    }
}

Upvotes: 3

Rap
Rap

Reputation: 7292

Depending on how you're exiting the program, you might consider using only nine timers and have the tenth activity part of the main thread of your code.

Each of those timers is a separate thread and should be handled carefully.

DoEvents is considered 'evil' and should be avoided. http://msdn.microsoft.com/en-us/library/system.windows.forms.application.doevents.aspx

Upvotes: 0

dicroce
dicroce

Reputation: 46800

You could wait on a condition variable, or select() on a socket.

Upvotes: 0

Related Questions