停止 C# 方法内的循环

发布于 2024-08-03 06:07:40 字数 511 浏览 3 评论 0原文

有什么方法可以停止另一个方法中的运行循环或在 C# 中动态插入break语句吗?

谢谢

编辑:我希望能够动态拦截该方法,并在另一个函数中触发事件时插入一个中断来停止循环。我有该类的多个实例,并且我想在需要时停止每个实例中的循环管理所有实例。考虑将多个实例放在通用列表中

示例:

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。

这是在 ASP.Net 应用程序中。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

花海 2024-08-10 06:07:40

如果整个事情都在单个线程中运行,那就没有任何意义。如果循环正在运行,则没有其他任何东西同时运行。如果您在另一个线程上运行循环并在另一个线程上运行控制方法,则可以完全中止循环线程或检查循环内的标志来决定是否应该中断并在控制方法中适当设置标志。

更新:使该函数返回一个布尔值,指示是否应该中断并在“if”语句中使用它:

if (myFunctionShouldBreakLoop()) break;

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;
幸福还没到 2024-08-10 06:07:40

另一种选择是在循环的每次迭代期间引发 CancelEventArgs。可能不是最有效的,但仍然是另一种选择:

    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;
                }
            }
        }

然后在其他地方:

myObj.LoopIncrement += MyHandler;

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

这样你可以从外部控制循环......

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....

天赋异禀 2024-08-10 06:07:40

具有上锁财产的条件。

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;
}

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;
}
¢蛋碎的人ぎ生 2024-08-10 06:07:40

不如使用迭代器和yield magic来解决这个问题。

这是一篇关于无限列表的文章,可能有用

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;
            }
        }
}

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;
            }
        }
}
烟凡古楼 2024-08-10 06:07:40

我认为你可以使用标志

bool stop = false;

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

I think you can use flag

bool stop = false;

for(int i=0;i<num;i++) 
{
 if(stop) break;
}
已下线请稍等 2024-08-10 06:07:40

简短的回答是:不。如果您不控制代码,则无法导致循环终止。

如果你确实控制了代码,你可以建立某种合作,但这听起来很混乱。也许你可以详细解释一下为什么?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文