Interrupt lengthy for loops I have this piece of code I would like some help with. I'm running a lengthy process that I want to interrupt at any time. The thing is, as you can see in the code, I have if(stop) everywhere, also in the methods inside the for (since they have for loops also).

stop is a member variable of the class, and the Stop() method is called from the UI from a different thread.

I don't think making it multithreading would be a good option since would be more complex to keep state and to communicate between threads.

Can you think of a better way to solve this, making the code cleaner?

public void Start()
{
    for(int i = 0; i &lt; Length; i++)
    {
        if(stop)
            return;

        LengthyMethodA();

        if(stop)
            return;

        LengthyMethodB();

        if(stop)
            return;

        LengthyMethodC();
    }
}

public void Stop()
{
    stop = true;
}
You could always set up a list of Actions that need to be worked on, and then loop through them checking for Stop each time.

Something like :

List&lt;Action&gt; actions = new List&lt;Action&gt; {
  () =&gt; LengthyMethodA(),
  () =&gt; LengthyMethodB(),
  () =&gt; LengthyMethodC() };

  for(int i = 0; i &lt; Length; i++)
  {    
    foreach (Action action in actions)
    {
       action();
       if(stop)
            return;
    }  
  }


This may or may not be better. It depends on the actual code. The actions list would represent an ordered set of transactional units of code - each unit must be completed, but the whole set can be broken apart and cancelled if necessary.