Winforms在单独的线程中执行代码 [英] Winforms execute code in separate thread

查看:80
本文介绍了Winforms在单独的线程中执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个少年问题...

我意识到在Winforms应用中,长时间运行的代码应在其自己的线程中执行.一个按钮单击事件如何做到这一点?

I realise that in a Winforms app, long running code should be executed in its own thread. How does one accomplish this on say, a button click event?

我想这样做是为了释放UI线程,以便我可以同时用半透明的模态对话框窗体覆盖当前窗体.我已经创建了一个模态对话框窗体,它的中央有一个整齐的加载GIF,可以很好地单独执行按钮单击事件.

I want to do this in an effort to free up the UI thread so that I can simultaneously overlay the current form with a semi-transparent modal dialog form. I've aleady created the modal dialog form with a neat loading GIF located in the centre that works perfectly on a button click event on its own.

之所以选择此方法,是因为(1)我想在执行代码时阻止用户与表单的任何交互,并且(2)向用户提供处理正在进行的指示(我不知道如何判断一段特定的代码将执行多长时间,因此选择了不确定的加载指示符(gif).

The reason I've chosen this method, is because (1) I want to block any user interaction with the form while the code is being executed, and (2) provide the user with an indication that processing is underway (I dont know how to judge how long a particular piece of code will take to execute, hence opting for an indefinite loading indicator gif).

此外,关于在单独的线程中执行代码的主题...这是否不适用于任何代码,或者仅适用于长时间运行的代码?

Also, on the topic of executing code in separate threads...should this not apply to any code, or only specifically to long-running code?

在此问题上的任何帮助,我将不胜感激!谢谢!

I would really appreciate any help on this matter! thank you!

推荐答案

最简单的方法之一是使用 BackgroundWorker 组件.将BackgroundWorker添加到您的窗体,为添加事件处理程序DoWork 事件,然后从那里调用长时间运行的函数.您可以通过调用在按钮单击事件处理程序中启动它. BackgroundWorker组件上的RunWorkerAsync 方法.

One of the simplest ways is to use a BackgroundWorker component. Add a BackgroundWorker to your form, add an event handler for the DoWork event, and call the long-running function from there. You can start it in your button click event handler by calling the RunWorkerAsync method on the BackgroundWorker component.

为了知道何时准备好操作,请为 RunWorkerCompleted 事件.

In order to know when the operation is ready, set up a handler for the RunWorkerCompleted event.

private void Button_Click(object sender, EventArgs e)
{
    myBackgroundWorker.RunWorkerAsync();
}

private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // long-running operation here; will execute on separate thread
}

private void myBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // operation is ready
}

这篇关于Winforms在单独的线程中执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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