主窗体停止响应
我编写了一个执行大量数学运算的函数,大约需要 10 分钟才能完成其工作。我尝试通过表单(Windows 表单应用程序)上的按钮调用此函数。但现在的问题是,在这10分钟内,主窗体停止响应,直到该功能完成其工作。
我该如何解决这个问题...任何想法!
I wrote a function that does alot of mathematical operations and it takes about 10 minutes to finish its work. I tried to call this function via a button on a form (Windows forms application). But the problem now is during the 10 minutes, the main form stops to respond till the function is finishing its work.
How can i solve this... any idea!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以为计算分配一个新线程,以便表单不必等待计算完成即可继续执行(即侦听和响应事件等)
You might assign a new thread for the calculations so that the form would not have to wait for the calculation to finish to continue execution (i.e. listening to and responding to events etc.)
问题是,当您的 10 分钟函数正在运行时,程序的其余部分并未执行。特别是,它无法执行渲染。 (即让您的表单做出响应)。
解决方案是使用线程。
The problem is that, while your 10 minute function is working, the rest of the program is not executed. In particular, it cannot execute the rendering. (i.e. making your form respond).
The solution is to use threads.
正如已经提到的,您应该将长时间运行的任务分配给工作线程或线程池线程。
请记住,线程池线程的数量是有限的。另外,Windows 窗体不是线程安全的,因此您不应该直接从创建的线程更新窗体。您可以使用 InvokeRequired。
As already mentioned you should assign long running tasks to a worker thread or a threadpool thread.
Keep in mind that there are limited numbers of threadpool thread. ALso Windows forms is not thread safe so you should not be directly updating the form from the created thread. You can make use of InvokeRequired.
在这种情况下最好使用BackgroundWorker类。详细信息请参见以下链接。
http://stuff.seans.com/2009/05/21/net-basics-do-work-in-background-thread-to-keep-gui-responsive/
In this case better to use BackgroundWorker class. Details in following link.
http://stuff.seans.com/2009/05/21/net-basics-do-work-in-background-thread-to-keep-gui-responsive/