在C#中的方法内停止循环 [英] Stop a loop inside a method in C#
问题描述
有什么方法可以停止另一个方法中的运行循环或在C#中动态插入break语句吗?
Is there any way to stop a running loop inside another method or insert a break statement dynamically in C#?
谢谢
我希望能够动态地拦截该方法并在一个事件在另一个函数中触发时插入一个中断以停止循环.我有该类的几个实例,并且我想在每个实例中每次都停止循环必需并管理所有实例.考虑将多个实例包含在通用列表中
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
示例:
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)
}
我需要这个,因为一旦用户存储了大量数据,我想打破循环.当用户导入数据时,我会触发一个事件.但是我无法继续从多个实例检查数据库,因为它破坏了sqlserver.
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.
这是在ASP.Net应用程序中.
This is in an ASP.Net application.
推荐答案
如果整个事情都在单个线程中运行,那将毫无意义.如果循环正在运行,则其他任何事物都不会同时运行.如果要在另一个线程上运行循环,并在另一个线程上运行控制方法,则可以完全中止循环线程,也可以检查循环内的标志来决定是否应该中断并在控制方法中适当地设置标志
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.
更新:使该函数返回一个布尔值,该布尔值指示您是否应该中断并在"if
"语句中使用它:
Update: make that function return a boolean value indicating whether you should break and use it in an "if
" statement:
if (myFunctionShouldBreakLoop()) break;
这篇关于在C#中的方法内停止循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!