Search code examples
c#loopsmethodsinterceptor

Stop a loop inside a method in C#


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.


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;