Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a console application that I would like to keep open all of the time while still listening in to events. I have tested Thread.Sleep(Timeout.Infinite); and while (true) { } and both allow the events to be raised while keeping the console application open. Is there one that I should be using over the other? If the thread is sleeping, is there anything that I should not be doing, such as modifying a static collection declared in the scope of the class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
618 views
Welcome To Ask or Share your Answers For Others

1 Answer

I would recommend using a ManualResetEvent (or other WaitHandle), and calling ManualResetEvent.WaitOne.

This will have a similar effect to sleeping forever, except that it provides you a clean way to exit from your infinite "block" when desired (by calling Set() on the event).

Using while(true) will consume CPU cycles, so it's definitely something to avoid.

is there anything that I should not be doing, such as modifying a static collection declared in the scope of the class?

In general, no. Since your thread will be blocked, there shouldn't be any synchronization issues with using shared data (provided the items within the collection don't have specific requirements, such as user interface elements which must be used on a thread with a proper synchronization context.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...