0

I have a while loop with a stopper:

public Myloop()
{ 
    bool execute == true;
    While (execute == true)
    {
        // do some stuff
        if (condidtion)
        {
            execute == false;
        }    
    }
}

and I'm calling in from another function after it stops:

Myloop.execute = true;

Will this be enough to restart the loop? if not, how can I restart it from another function easy way?

2
  • bool execute = true; is how you assign the value. Commented Jan 6, 2017 at 9:08
  • 1
    once execute is set to false. the loop ends. why not call myLoop again when needed? Commented Jan 6, 2017 at 9:13

3 Answers 3

2

No, Once a while loop is done it wont start again until you run the Myloop() function again:

public void RunLoopTwice(){
    MyLoop();
    MyLoop(); 
}

public void Myloop()
{
    bool execute = true;
    while (execute == true)
    {
        // do some stuff
        if (condition)
        {
            execute = false;
        }
    }
}

Also normally code is executed in a synchronous order, so only 1 piece of code is executed at the time. with async/await, Task or Thread you can make multiple pieces of code run at once. If you are using any of this, you need to make sure you properly lock pieces of code to not get any race conditions.

Sign up to request clarification or add additional context in comments.

Comments

2

You are confusing == and = operators, == is for comparison while = is for assignment. Read about C# Operators.

public void Myloop()
{
    bool execute = true;
    while (execute == true)
    {
        // do some stuff
        if (condition)
        {
            execute = false;
        }
    }
}

Simpler way to do this is using break since you are not returning the value of execute field. Once the condition is met, while loop will terminate.

while (true)
{
    // do some stuff
    if (condition) break;
}

And you call the method using Myloop(); not Myloop.execute = true;.

Comments

0

You can do with two flags but this code will be run on the different thread because this code will go in the infinite loop.

For Ex.

public bool doLoop = true;
public bool doProcess = true;

public void MyLoop()
{
   while(doLoop)
   {
      while(doProcess)
      {
         // do some stuff
         if (condition)
         {
            doProcess = false;
         }
      }
    }
}

After your need is completed than make doLoop false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.