如何使进度条在C#中的不同线程中运行 [英] How to make a progressbar run in a different thread in C#

查看:296
本文介绍了如何使进度条在C#中的不同线程中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用进度条创建一个基本的多线程应用程序.这意味着当主线程正在执行的大型进程处于繁忙状态时,该进度条将在其他线程上运行.我看过很多关于它的教程.但是它们是多线程的事情就是执行大型进程的事情.另一种形式的进度条仅显示了一个简单的进度条,该进度条使用计时器运行并完成.

I want to create a basic multi-thread application using a progress bar. Meaning that this progress bar will run on a different thread while the main thread is busy in the large process it is doing. I've seen a lot of tutorials about it. But the thing that they are multi-threading is the one that doing the large process. The progress bar in the other form is just showing a simple progress bar that runs and complete using a timer.

这是我现在拥有的代码.

This is the code I have now.

对于线程:

public void thread()
{
  Form6 for6 = new Form6();
  for6.Show();
}


TH1 = new Thread(thread);
TH1.Start();

用于进度条(表格6中的代码)

For the progress bar (Code inside form 6)

 private void timer1_Tick(object sender, EventArgs e)
    {
        progressBar1.Increment(+1);
        if (progressBar1.Value == 99)
        {
            this.Close();
        }
    }

    private void Form6_Load(object sender, EventArgs e)
    {
        timer1.Start();
    }

我的问题是这里的线程没有运行Form6.我有什么办法吗?

My problem is the thread in here doesn't run the Form6. Is there any way for me to do this?

推荐答案

您应该真正将长时间运行的非UI代码移到单独的线程中,而不要使用ProgressBar.在WinForms中执行此操作的标准且更简单的方法是使用BackgroundWorker组件,该组件可以引发ProgressChanged事件,您可以在其中更新您的UI.重要的是要注意,ProgressChanged事件是在UI线程上引发的,而不是在工作线程上引发的,因此,您甚至不需要使用Invoke()来执行UI操作(例如更新ProgressBar).

Instead of the ProgressBar, you should really move your long-running, non-UI code into a separate thread. The standard and easier way of doing this in WinForms is to use BackgroundWorker component, which can raise ProgressChanged event where you can update your UI. Important to note that ProgressChanged event is raised on the UI thread, not on the worker thread, so you don't even need to use Invoke() to perform UI operations (such as updating your ProgressBar).

这篇关于如何使进度条在C#中的不同线程中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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