HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Interrupt lengthy for loops

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lengthyinterruptforloops

Problem

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 < Length; i++)
    {
        if(stop)
            return;

        LengthyMethodA();

        if(stop)
            return;

        LengthyMethodB();

        if(stop)
            return;

        LengthyMethodC();
    }
}

public void Stop()
{
    stop = true;
}

Solution

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 actions = new List {
  () => LengthyMethodA(),
  () => LengthyMethodB(),
  () => LengthyMethodC() };

  for(int i = 0; i < 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.

Code Snippets

List<Action> actions = new List<Action> {
  () => LengthyMethodA(),
  () => LengthyMethodB(),
  () => LengthyMethodC() };

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

Context

StackExchange Code Review Q#899, answer score: 8

Revisions (0)

No revisions yet.