如何在c#windows应用程序中退出循环 [英] How to exit a loop in c# windows application

查看:90
本文介绍了如何在c#windows应用程序中退出循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的c#windows应用程序中有一个启动和停止按钮。按下启动按钮后,将执行两个For循环。在停止按钮上单击我也需要在循环可能的任何地方退出这些循环。但是在我的应用程序中,在开始按钮中输入循环后单击我无法单击任何其他按钮来停止进程。任何人都可以解释这是否发生了这个问题?

解决方案

你必须使用后台工人类 - http://stuff.seans.com/2009/05/21/net-basics-do-work-in-background-thread-to-keep-gui-responsive/ [ ^ ]。


实际上,这个问题与您的循环或您为应用程序定义的业务逻辑无关。相反,在您正在使用的这些框架中,只有一个线程应用程序可以执行所有逻辑执行,并使UI响应。因此,只要这些循环正在运行,UI线程将无法执行,使得所有UI(包括按钮,TextBoxes)都被冻结。



这里需要的是在任何其他线程中执行这些循环,这些循环将在后台运行。线程可以是可以在后台执行的此类过程的示例。你可以使用它在后台运行代码(异步)让你的应用程序保持响应能力(能够收到Button,TextBox等的点击)。



我写的另一个答案描绘了相同的条件和问题。您可能有兴趣阅读我的答案。请阅读:如何safley给我的功能而不会让我的主表格卡住 [ ^ ]



一旦用户界面响应,你可以点击用于终止循环的按钮, break 如果你想只打破循环,或者停止线程本身等等。这取决于你的需要。




您需要使用踏板来启动和停止操作。

谢谢


i have a start and stop button in my c# windows application. After pressing start button two For loops will be executed. On Stop button click i need too Quit those loops wherever the loop may be. But in my application after the entering the loop in Start button click i am unable to click any other button to stop the process.can any one explain the y is it happening lyk this?

解决方案

You have to use the background worker class - http://stuff.seans.com/2009/05/21/net-basics-do-work-in-background-thread-to-keep-gui-responsive/[^].


Actually this problem is not with your loop or the business logic you're defining for your application. Instead in these frameworks that you're using there is only one thread-ed application which performs all of the logical executions and also makes the UI responsive. So, as long as those loops are running the UI thread won't be able to execute, making all of the UI (including buttons, TextBoxes) frozen.

What you need here, is to execute those loops in any other thread, which would run in the background. Thread can be an example of such process that can be executed in the background. You can use this to run the code in background (asynchronously) to let your application stay responsiveness (able to recieve clicks on Button, TextBox etc).

I have written another answer to depict the same condition and problem. You might be interested in reading that answer of mine. Do give this a read: How to safley give my function without making my main form stuck[^]

Once the UI is responsive, you can click on the button to terminate the loop using, break if you want to break the loop only, or stop the thread itself etc. It depends on your need.


Hi,
Instead of buttons, you need to use treads for starting and stopping your operation.
Thanks


这篇关于如何在c#windows应用程序中退出循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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