是Thread.Sleep(Timeout.Infinite);比while(true){}更有效? [英] Is Thread.Sleep(Timeout.Infinite); more efficient than while(true){}?

查看:182
本文介绍了是Thread.Sleep(Timeout.Infinite);比while(true){}更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序,我想一直保持打开状态,同时仍然监听事件。我已经测试了 Thread.Sleep(Timeout.Infinite); while(true){} 都允许事件在保持控制台应用程序打开的同时进行。我是否应该使用另一个?如果线程正在睡眠,我有什么不应该做的事情,例如修改在类范围内声明的静态集合?

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?

推荐答案

我建议使用 ManualResetEvent (或其他 WaitHandle ),然后调用 ManualResetEvent.WaitOne

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

此它将与永久休眠具有相似的效果,不同之处在于,它为您提供了一种在需要时从无限块退出退出的干净方法(通过调用事件中的 Set() )。

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).

使用 while(true)会消耗CPU周期,因此绝对可以避免。

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


有什么我不应该做的事情,例如修改在cla范围内声明的静态集合ss?

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.)

这篇关于是Thread.Sleep(Timeout.Infinite);比while(true){}更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆