Question

Is there any way to stop a running loop inside another method or insert a break statement dynamically in C#?

Thanks

Edit : I want to be able to dynamically intercept the method and insert a break to stop the loop when an event gets triggered in another function.I have several instances of the class and I want to stop the loop in each instance whenever required and manage all the instances. Consider multiple instances to be in a generic list

Example :

List<myclass> objlist=new List<myclass>();

foreach(myclass obj in objlist)
{
obj.loopingfunction().BreakLoop //or something like this (assuming that the loopingfunction is already called)
}

I need this because I want to break the loop once the user stores some huge amount of data.When the user imports the data,I get a event fired. But I cannot keep checking the database from multiple instances since it screws up sqlserver.

This is in an ASP.Net application.

Was it helpful?

Solution

If the whole thing is running in a single thread, it wouldn't make any sense. If the loop is running, then nothing else is running at the same time. If you're running a loop on another thread and the controlling method on another thread, you can either abort the loop thread completely or check a flag inside the loop to decide whether or not you should break and set the flag appropriately in the controlling method.

Update: make that function return a boolean value indicating whether you should break and use it in an "if" statement:

if (myFunctionShouldBreakLoop()) break;

OTHER TIPS

Another option would be to raise a CancelEventArgs during every iteration of the loop. Probably not the most efficient, but another option nonetheless:

    private void SomeMethod()
    {
        for (int i = 0; i <= 100000; i++)
        {
            Console.WriteLine(i);
            if (LoopIncrement != null)
            {
                CancelEventArgs args = new CancelEventArgs();
                LoopIncrement(null, args);
                if (args.Cancel)
                {
                    break;
                }
            }
        }

And then elsewhere:

myObj.LoopIncrement += MyHandler;

private void MyHandler(object sender, CancelEventArgs e)
{
   if(someCondition)
   {
      e.Cancel = true;
   }
}

This way you can somewhat control the loop from outside....

Have the condition in a locked property.

private Boolean BreakCondition
{
    get { lock(_LockObject) { return _BreakCondition; }  }
    set { lock(_LockObject) { _BreakCondition = value; }  }
}
private Boolean _BreakCondition = false;
private Object _LockObject = new Object();


if (this.BreakCondition)
{
    break;
}

How about using iterators, and yield magic to solve the problem.

Here is an article on infinite lists that might be useful

http://www.codethinked.com/post/2009/02/04/Infinite-Lists-With-C-Yield.aspx

 class Program
    {
        static void Main(string[] args)
        {
            Predicate<int> when = i => i > 100 && Console.ReadKey().KeyChar.ToString() == "0";

            foreach(var i in Numbers().BreakOn(when))
            {
                Console.WriteLine(i);
            }

            Console.ReadLine();
        }

        private static IEnumerable<int> Numbers()
        {
            var i = 0;
            while(true)
            {
                yield return i++;
            }
        }


    }

    public static class Util
    {
        public static IEnumerable<int> BreakOn(this IEnumerable<int> sequence, Predicate<int> when)
        {
            foreach(int i in sequence)
            {
                if(when(i))
                {
                    yield break;
                }
                yield return i;
            }
        }
}

I think you can use flag

bool stop = false;

for(int i=0;i<num;i++) 
{
 if(stop) break;
}

The short answer is: no. If you don't control the code, then you can't cause the loop to terminate.

If you do control the code, you could build in some sort of cooperation, but it sounds messy. Maybe you can elaborate on why?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top