Brandon Moore
Brandon Moore

Reputation: 8780

What's the right way to keep my program from ending while waiting on events

I have an app that sets some events and needs to wait for those events to occur before exiting. What's the best way do this? I understand that Thread.Sleep is a poor choice for various reasons including the fact that it won't even be able to process events if it's sleeping. I obviously don't won't to waste cpu cycles with a while loop that does nothing. So what's the simplest way to prevent a console app from exiting for an indeterminate amount of time so it can process events as they are raised?

Ultimately this is going to be a service which will make this a non-issue but right now on my first iteration I'm just testing out some of my code in a console app before I go through the trouble of making it into a real service (haven't made a service before so I'd like to make sure my code is solid so as not to complicate the next step). As I'm writing this I just realized I could have just tested it in a WinForms app instead and that would solve my problem, duh.

Upvotes: 3

Views: 471

Answers (2)

HABO
HABO

Reputation: 15816

I've built on this to write services that can also be run, and debugged, as console applications.

The "make it more complicated" approach didn't work for me either.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564323

A good option is to use a ManualResetEvent. This allows you to block while waiting for the event to be set, without sleeping. The main routine of your console application can call WaitOne() on the ManualResetEvent, which will block. When your routine finishes, just call ManualResetEvent.Set() to allow the console application to shut down.

If you need to wait on a collection of events, CountdownEvent is another option. You can call AddCount() and Signal to increase and decrease the count as needed.

Upvotes: 1

Related Questions