停在一个winform点击按钮执行的功能 [英] stopping a function executed on a winform button click

查看:247
本文介绍了停在一个winform点击按钮执行的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 在一个简单的WinForm应用程序,我称之为endlessy上一个按钮单击事件创建文件的功能。我想补充Application.DoEvents()来循环。

  1. In a simple winform application, I call a function that endlessy create files on a button click event. I add Application.DoEvents() to the loop.

我按下红色的X关闭该窗体。

I press the red X to close the form.

窗体关闭,但文件继续创建...

the form closes, but files continue to be created ...

我认为它按钮线程,但它不应该是一个背景呢?试图改变Thread.CurrentThread.IsBackGround为True环路功能没有帮助。

I think its on the buttons thread, but shouldnt it be a background one ? trying changing Thread.CurrentThread.IsBackGround to True on the loop function does not help.

想法?

推荐答案

这是您正在使用的事实 Application.DoEvents 是一个问题的第一个迹象:它表明你正在做太多UI线程。这是一个结构良好的程序几乎没有合适的。 UI线程并不意味着有任何长时间运行的任务。 (诚​​然,如果它需要很长的时间来绘制你的UI,你别无选择 - 但建议你应该简化的用户界面......,这不是适用在这种情况下,我怀疑)

The fact that you're using Application.DoEvents is the first sign of a problem: it shows that you're doing too much in the UI thread. It's almost never appropriate in a well-structured program. The UI thread is not meant to have any long-running tasks. (Admittedly if it takes a long time to draw your UI you have little choice - but that suggests you should simplify your UI... and it's not applicable in this case, I suspect.)

相反,你应该执行长时间运行的任务(创建文件)在一个单独的线程。 BackgroundWorker的是这一个完美的结合 - 您可以使用它报告进度回到UI,并且UI可以调用的 CancelAsync 方法来请求停止。您需要查看 CancellationPending 财产工作者线程内,看看是否取消已请求,并适当地停止

Instead, you should be performing the long-running task (creating the files) in a separate thread. BackgroundWorker is a perfect fit for this - you can use it to report progress back to the UI, and the UI can call CancelAsync method to request that it stops. You need to check the CancellationPending property from within the worker thread, to see whether cancellation has been requested, and stop appropriately.

编辑:只是为了澄清什么我相信发生的一切 - 我怀疑你的形式关闭,但该计划不会终止,直到事件循环已经完成。 。你保持事件循环与你的文件创建循环,因此,这个问题将

Just to clarify what I believe is happening - I suspect your form is closing, but the program won't terminate until the event loop has finished. You're keeping the event loop going with your file-creation loop, hence the problem.

请注意,有没有为按钮的线程 - 有只有我一个你的整个UI。 (在某些情况下,可能需要多个UI线程,但是这是罕见的 - 而且你知道,如果你做到了)

Note that there isn't a thread for the button - there's just one for your whole UI. (In certain cases you may need more than one UI thread, but that's rare - and you'd know it if you'd done it.)

这篇关于停在一个winform点击按钮执行的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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