C#按下按钮中断了循环 [英] C# Break out of loop on button press

查看:923
本文介绍了C#按下按钮中断了循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的C#foreach循环,我怎么能摆脱循环当按下按钮?它不是一个BackgroundWorker的线程,所以我不能用backgroundWorker.CancellationPending。

I have a simple C# foreach loop, how can I break out of the loop when a button is pressed? It is not in a backgroundWorker thread so I can't use backgroundWorker.CancellationPending.

推荐答案

创建于形式的布尔标志。附加一个事件处理程序的按钮单击事件和标志设置为true在事件处理程序。

Create a boolean flag in the form. Attach an event handler to the buttons click event and set the flag to true in the event handler.

检查在循环中的标志,如果这是真的,叫破发。 (一个更好的选择是使用while循环,而不是一个for循环旗在while条件检查)

Check for the flag in the loop and if it's true, call "break". (A better option would be to use a while loop instead of a for loop with the check of the flag in the while condition)

显然for循环将需要某种形式的后台线程上,否则GUI将无法响应。如果你不知道如何做到这一点,检查出任何的 ThreadPool.QueueUserWorkItem BackgroundWorker的 。如果你使用一个BackgroundWorker,你可以使用,而不是编码自己取消标志内置的CancelAsync()方法。

Obviously the for loop will need to be on some form of background thread otherwise the GUI won't be responsive. If you don't know how to do this, check out either ThreadPool.QueueUserWorkItem or the BackgroundWorker. If you do use a BackgroundWorker you can use the inbuilt CancelAsync() method instead of coding your own cancel flag.

[不要忘记你之前设置了标志的正确状态开始循环。]

[Don't forget to set the correct state of the flag before you start the loop.]

这篇关于C#按下按钮中断了循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆