C# while loop
In C# while-loop is used very similar to other programming languages. Here is an example which demonstrate the performance and impact on CPU utilization. There must be a condition in loop which will terminate the loop. other wise program will go in infinite loop and it will consume more 100% of CPU resource.
As shown in image below you can see, as soon as we run program CPU utilization goes to top almost 100% consumption. It's like racing bike without any load. Bike may went to burn, same way CPU can burn.
While loop in [c#]
C# program example of while loop
using System;
namespace Csharp.While.Example
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("This is infinite while loop example");
}
}
}
}
VB.net program using while loop
Namespace Csharp.While.Example
Class Program
Private Shared Sub Main(args As String())
While True
Console.WriteLine("This is infinite while loop example")
End While
End Sub
End Class
End Namespace
Avoid using infinite while loops.
C# While loop with condition
Example uses array of strings. When input element found we are breaking the loop to stop further execution.
using System;
namespace Csharp.While.Example
{
class Program
{
static void Main(string[] args)
{
string[] arrOfStrings = new string[] { "Program", "C#", "VB.net", "More", "Code" };
int counter = 0;
while (true)
{
if (arrOfStrings[counter] == "VB.net")
break;
Console.WriteLine("Element {0}", arrOfStrings[counter]);
counter++;
}
Console.ReadLine();
}
}
}
(VB.net) while-loop example
Namespace Csharp.While.Example
Class Program
Private Shared Sub Main(args As String())
Dim arrOfStrings As String() = New String() {"Program", "C#", "VB.net", "More", "Code"}
Dim counter As Integer = 0
While True
If arrOfStrings(counter) = "VB.net" Then
Exit While
End If
Console.WriteLine("Element {0}", arrOfStrings(counter))
counter += 1
End While
Console.ReadLine()
End Sub
End Class
End Namespace
Output program.
Element Program
Element C#
Index was outside the bounds of the array.
The example above is wrong way of using while loop. Imagine if there is no element found in array of strings. The program will try to get an element which is out of reach and throws an exception.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5