空的while循环有什么作用? [英] What is the effect of having an empty while loop?

查看:928
本文介绍了空的while循环有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是一个愚蠢"的问题,但是有时候,我只想循环直到条件为假,但我不喜欢让循环为空.因此,而不是:

Visible = true;
while(IsRunning)
{
}
Visible = false;

我通常 prefer :

while(IsRunning)
{
    Visible = true;
}
Visible = false;

但是,我有点担心Visible = true;行会发生什么.即使它是 redundant ,运行时是否仍会继续执行该语句?这样甚至可以做到吗?许多代码增强"插件不喜欢空的while循环,我也不十分清楚为什么.

SO:

  • 有一个空的while循环有什么问题吗?

  • 具有如上所示的循环会产生任何性能影响吗?

谢谢!

解决方案

这称为忙碌或旋转等待.

主要问题是,您正在阻塞线程,正在运行此while循环.如果此线程是GUI线程,则将导致冻结和不负责任的GUI.是的,这会导致性能损失,因为编译器和OS都无法知道他们是否可以通过某种方式优化while循环.

只需尝试像这样进行单循环,看看CPU的一个内核如何以100%的速度运行.

执行此操作的正确方法是使用异步编程,在异步操作中,当上一个操作完成运行时,可以通过事件或语言构造(例如await)来通知您的代码.

但是它通常在低级系统或语言中使用. .NET 4.0引入了 SpinWait 构造,该构造可作为有效的线程同步机制. /p>

关于您的问题.我相信都不应该使用.它们在调试,性能和代码清晰度方面都存在问题.

I know this might be a bit of a 'silly' question, but sometimes, I just want to loop until a condition is false but I don't like keeping the loop empty. So instead of:

Visible = true;
while(IsRunning)
{
}
Visible = false;

I usually prefer:

while(IsRunning)
{
    Visible = true;
}
Visible = false;

However, I'm a bit concerned about what exactly happens at the line Visible = true;. Does the Runtime keep executing that statement even though it's redundant? Is it even advisable to do it this way? Many 'code-enhancements' plugins don't like empty while loops, and I don't really understand why.

SO:

  • Is there anything wrong with having an empty while loop?

  • Does having a loop such as shown above have any performance effects?

Thanks!

解决方案

This is called busy or spin waiting.

The main problem is, that you are blocking the thread, that is running this while loop. If this thread is GUI thread, then it will result in freezing and unresponsible GUI. And yes, this results in loss of performance, because neither compiler, nor OS can know if they can somehow optimize this while loop.

Just try making single loop like this and see how one core of your CPU is running at 100%.

The right way to do this is to use asynchronous programming, where your code gets notified, either by event or language construct (like await) when the previous operation finished running.

But it is usually used in low-level systems or languages. .NET 4.0 introduces SpinWait construct, that serves as efficient threading sychnronization.

And in relation to your question. I believe neither should be used. They are both problematic for both debugging, performance and clarity of code.

这篇关于空的while循环有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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