Can you give me an infinite loop example on c# with minimum code? I came up with something but I thought there co开发者_开发知识库uld be more easier way.
The typical examples are the for and while loops. For example
for(;;)
{}
and
while(true)
{}
However, basically any looping construct without a break or a terminating condition will loop infinitely. Different developers have different opinions on which style is best. Additionally, context may sway which method you choose.
while (true);
That should be enough.
The generated IL is:
IL_0000: br.s IL_0000
The code unconditionally transfers control to itself. A great way to waste CPU cycles.
Infinite loop:
while (true)
{
// do stuff
}
to break it:
while (true)
{
if (condition)
break;
}
If you need a bit more obscurity, this might be what you are after:
for (;;) { }
Or even
l: goto l;
In the spirit of Code Golf:
for(;;);
Though not exactly an infinite loop, this will have the same practical effect and consume WAY less CPU. :)
System.Threading.Thread.Sleep(-1);
Try this, an example of infinite loop.
while(true)
{
}
Call a method within the same method and you have an infinite loop happening (Only conditions force you to break the loop)
void HelloWorld()
{
HelloWorld();
}
精彩评论