hi
while(true)
{
i need a partcular section of code runs only once
}
Printable View
hi
while(true)
{
i need a partcular section of code runs only once
}
Remove the while(true) { and ending } and the code will only execute once.
Do you know about the break statement?
As Norm mentioned, there is not need for a while if you only need the code to execute once. If you need the code to execute at least once, the use do{} while()
I need to use while loop as its the threads run method ,
but in that loop i want a section of code to ecxecute once , or for a particular count..
public Run()
{
while(true)
{
[ this section of code runs for 200 counts]
[this scode runs only once]
}
If the section of code is inside the while loop, then use a boolean oneTime switch in an if statement
Define the boolean variable as true outside the loop. The inside the loop:
Code :if (oneTime) { oneTime = false; // flip the switch to prevent execution next loop around // do the one time stuff } // end if
I don't see why it has to be inside the while loop - surely only the code that needs to run many times should be in the loop. One-time code should be before or after the loop, as appropriate.
Also, if you need code executed 200 times, why not use a 'for..' loop that counts 200 iterations? A 'while(true)' loop is really only suitable for loops with an indefinite number of repeats (and not particularly good practice).