WinForm 应用程序 UI 在长时间运行期间挂起 [英] WinForm Application UI Hangs during Long-Running Operation

查看:53
本文介绍了WinForm 应用程序 UI 在长时间运行期间挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 windows 窗体应用程序我需要使用 for 循环进行大量远程调用,大约 2000 - 3000 次调用,

I have a windows forms application on which I need to use a for loop having a large number of Remote Calls around 2000 - 3000 calls,

并且在执行 for 循环时,我失去了对表单和表单控件的控制,因为它变成了一个大进程,并且有一段时间它显示无响应",但如果我等了很长时间它又回来了,我想我需要为此使用一些线程模型,有什么想法,我该如何继续解决问题?

and while executing the for loop, I loose my control on form and form controls, as it becomes a large process and some time it shows "Not Responding" but if I wait for a long it comes back again, I think I need to use some threading model for that, is there any idea, how can I proceed to solve the issue?

推荐答案

您需要在后台线程上执行长时间运行的操作.

You need to perform the long running operation on a background thread.

有几种方法可以做到这一点.

There are several ways of doing this.

  1. 您可以将方法调用排队以在线程池线程上执行(请参阅此处):

ThreadPool.QueueUserWorkItem(new WaitCallback(YourMethod));

在 .NET 4.0 中,您可以使用 TaskFactory:

In .NET 4.0 you can use the TaskFactory:

Task.Factory.StartNew(() => YourMethod());

在 .NET 4.5 及更高版本中,您可以(并且应该,而不是 TaskFactory.StartNew())使用 Task.Run():

And in .NET 4.5 and later, you can (and should, rather than TaskFactory.StartNew()) use Task.Run():

Task.Run(() => YourMethod());

  • 您可以使用 BackgroundWorker如果您需要进度更新或完成时的通知,则可以更好地控制该方法.将 BackgroundWorker 控件拖到您的表单上,并将您的方法附加到 dowork 事件.然后在您想要运行您的方法时启动工作程序.您当然可以从代码中手动创建 BackgroundWorker,但请记住,完成后需要对其进行处理.

  • You could use a BackgroundWorker for more control over the method if you need things like progress updates or notification when it is finished. Drag the a BackgroundWorker control onto your form and attach your method to the dowork event. Then just start the worker when you want to run your method. You can of course create the BackgroundWorker manually from code, just remember that it needs disposing of when you are finished.

    为您的工作创建一个全新的线程.这是最复杂的并且不是必需的,除非您需要对线程进行真正细粒度的控制.如果需要,请参阅 Thread 类上的 MSDN 页面了解这一点.

    Create a totally new thread for your work to happen on. This is the most complex and isn't necessary unless you need really fine grained control over the thread. See the MSDN page on the Thread class if you want to learn about this.

    请记住,对于任何线程,您不能更新 GUI,或从后台线程更改任何 GUI 控件.如果您想在 GUI 上执行任何操作,您必须使用 Invoke(和 InvokeRequired)在 GUI 线程上触发该方法.请参阅此处.

    Remember that with anything threaded, you cannot update the GUI, or change any GUI controls from a background thread. If you want to do anything on the GUI you have to use Invoke (and InvokeRequired) to trigger the method back on the GUI thread. See here.

    这篇关于WinForm 应用程序 UI 在长时间运行期间挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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