在 C# 中做一些工作时显示进度条?

发布于 2024-08-15 18:32:42 字数 1259 浏览 2 评论 0原文

我想在做一些工作时显示进度条,但这会挂起 UI 并且进度条不会更新。

我有一个带有 ProgressBar 的 WinForm ProgressForm,它将以 ma​​rquee 方式无限期地继续。

using(ProgressForm p = new ProgressForm(this))
{
//Do Some Work
}

现在有很多方法可以解决这个问题,比如使用BeginInvoke,等待任务完成并调用EndInvoke。或者使用BackgroundWorkerThreads

我在 EndInvoke 方面遇到了一些问题,但这不是问题所在。问题是,哪种方法是处理这种情况的最佳和最简单的方法,您必须向用户表明程序正在运行而不是无响应,以及如何使用最简单的代码来处理这种情况,既高效又成功。不会泄漏,并且可以更新GUI。

就像 BackgroundWorker 需要具有多个函数、声明成员变量等。此外,您还需要保存对 ProgressBar Form 的引用并处理它。

编辑BackgroundWorker不是答案,因为我可能没有收到进度通知,这意味着不会调用ProgressChanged 因为 DoWork 是对外部函数的一次调用,但我需要继续调用 Application.DoEvents(); 以使进度条继续旋转。

赏金是针对这个问题的最佳代码解决方案。我只需要调用 Application.DoEvents() 即可使 Marque 进度条正常工作,而工作函数在主线程中工作,并且不会返回任何进度通知。我从来不需要 .NET 魔术代码来自动报告进度,我只是需要一个比以下更好的解决方案:

Action<String, String> exec = DoSomethingLongAndNotReturnAnyNotification;
IAsyncResult result = exec.BeginInvoke(path, parameters, null, null);
while (!result.IsCompleted)
{
  Application.DoEvents();
}
exec.EndInvoke(result);

使进度条保持活动状态(意味着不冻结而是刷新品牌)

I want to display a progress bar while doing some work, but that would hang the UI and the progress bar won't update.

I have a WinForm ProgressForm with a ProgressBar that will continue indefinitely in a marquee fashion.

using(ProgressForm p = new ProgressForm(this))
{
//Do Some Work
}

Now there are many ways to solve the issue, like using BeginInvoke, wait for the task to complete and call EndInvoke. Or using the BackgroundWorker or Threads.

I am having some issues with the EndInvoke, though that's not the question. The question is which is the best and the simplest way you use to handle such situations, where you have to show the user that the program is working and not unresponsive, and how do you handle that with simplest code possible that is efficient and won't leak, and can update the GUI.

Like BackgroundWorker needs to have multiple functions, declare member variables, etc. Also you need to then hold a reference to the ProgressBar Form and dispose of it.

Edit: BackgroundWorker is not the answer because it may be that I don't get the progress notification, which means there would be no call to ProgressChanged as the DoWork is a single call to an external function, but I need to keep call the Application.DoEvents(); for the progress bar to keep rotating.

The bounty is for the best code solution for this problem. I just need to call Application.DoEvents() so that the Marque progress bar will work, while the worker function works in the Main thread, and it doesn't return any progress notification. I never needed .NET magic code to report progress automatically, I just needed a better solution than :

Action<String, String> exec = DoSomethingLongAndNotReturnAnyNotification;
IAsyncResult result = exec.BeginInvoke(path, parameters, null, null);
while (!result.IsCompleted)
{
  Application.DoEvents();
}
exec.EndInvoke(result);

that keeps the progress bar alive (means not freezing but refreshes the marque)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

彼岸花ソ最美的依靠 2024-08-22 18:32:42

在我看来,您至少在一个错误的假设上进行操作。

1.您不需要引发 ProgressChanged 事件来拥有响应式 UI

在您的问题中,您这样说:

BackgroundWorker 不是答案
因为我可能不明白
进度通知,这意味着
不会有任何电话
ProgressChanged 因为 DoWork 是
对外部函数的单次调用。
。 .

实际上,是否调用 ProgressChanged 事件并不重要。该事件的全部目的是暂时将控制权转移回 GUI 线程以进行更新,以某种方式反映 BackgroundWorker 正在完成的工作进度。 如果您只是显示一个选取框进度条,那么引发 ProgressChanged 事件实际上是毫无意义的。只要显示,进度条就会继续旋转,因为 BackgroundWorker 正在与 GUI 分开的线程上执行其工作

(顺便说一句,DoWork 是一个事件,这意味着它不仅仅是“对外部函数的一次调用”;您可以添加任意数量的处理程序就像;并且每个处理程序都可以包含任意数量的函数调用。)

2. 您不需要调用 Application.DoEvents 来拥有响应式 UI

对我来说,听起来您相信唯一 GUI 更新的方式是调用 Application.DoEvents

我需要继续打电话
应用程序.DoEvents();为
进度条继续旋转。

在多线程场景中情况并非如此;如果您使用 BackgroundWorker,GUI 将继续响应(在其自己的线程上),同时 BackgroundWorker 执行附加到其 DoWork 事件。下面是一个简单的示例,说明这可能如何为您服务。

private void ShowProgressFormWhileBackgroundWorkerRuns() {
    // this is your presumably long-running method
    Action<string, string> exec = DoSomethingLongAndNotReturnAnyNotification;

    ProgressForm p = new ProgressForm(this);

    BackgroundWorker b = new BackgroundWorker();

    // set the worker to call your long-running method
    b.DoWork += (object sender, DoWorkEventArgs e) => {
        exec.Invoke(path, parameters);
    };

    // set the worker to close your progress form when it's completed
    b.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => {
        if (p != null && p.Visible) p.Close();
    };

    // now actually show the form
    p.Show();

    // this only tells your BackgroundWorker to START working;
    // the current (i.e., GUI) thread will immediately continue,
    // which means your progress bar will update, the window
    // will continue firing button click events and all that
    // good stuff
    b.RunWorkerAsync();
}

3.你不能在同一个线程上同时运行两个方法

你这样说:

我只需要打电话
Application.DoEvents() 以便
Marque 进度条将起作用,同时
工作函数在 Main 中工作
线 。 。 .

您所要求的根本不是真实的。 Windows 窗体应用程序的“主”线程是 GUI 线程,如果它忙于长时间运行的方法,则不会提供可视更新。如果您不这么认为,我怀疑您误解了 BeginInvoke 的作用:它在单独的线程上启动委托。事实上,您在问题中包含的在 exec.BeginInvokeexec.EndInvoke 之间调用 Application.DoEvents 的示例代码是多余的;您实际上是从 GUI 线程重复调用 Application.DoEvents无论如何都会更新。 (如果您发现其他情况,我怀疑这是因为您立即调用了 exec.EndInvoke,这会阻塞当前线程,直到该方法完成。)

所以是的,您正在寻找的答案是使用后台工作人员

可以使用BeginInvoke,但不要从GUI线程调用EndInvoke(如果方法未完成,这将阻止它),而是传递向您的 BeginInvoke 调用添加一个 AsyncCallback 参数(而不是仅仅传递 null),并在回调中关闭进度表单。但是请注意,如果这样做,您将必须调用从 GUI 线程关闭进度表单的方法,否则您将尝试从 GUI 线程关闭表单(这是一个 GUI 函数)。非 GUI 线程。但实际上,使用 BeginInvoke/EndInvoke 的所有陷阱都已经通过 BackgroundWorker 类为您解决了 ,即使您认为它是“.NET 魔法代码”(对我来说,它只是一个直观且有用的工具)。

It seems to me that you are operating on at least one false assumption.

1. You don't need to raise the ProgressChanged event to have a responsive UI

In your question you say this:

BackgroundWorker is not the answer
because it may be that I don't get the
progress notification, which means
there would be no call to
ProgressChanged as the DoWork is a
single call to an external function .
. .

Actually, it does not matter whether you call the ProgressChanged event or not. The whole purpose of that event is to temporarily transfer control back to the GUI thread to make an update that somehow reflects the progress of the work being done by the BackgroundWorker. If you are simply displaying a marquee progress bar, it would actually be pointless to raise the ProgressChanged event at all. The progress bar will continue rotating as long as it is displayed because the BackgroundWorker is doing its work on a separate thread from the GUI.

(On a side note, DoWork is an event, which means that it is not just "a single call to an external function"; you can add as many handlers as you like; and each of those handlers can contain as many function calls as it likes.)

2. You don't need to call Application.DoEvents to have a responsive UI

To me it sounds like you believe that the only way for the GUI to update is by calling Application.DoEvents:

I need to keep call the
Application.DoEvents(); for the
progress bar to keep rotating.

This is not true in a multithreaded scenario; if you use a BackgroundWorker, the GUI will continue to be responsive (on its own thread) while the BackgroundWorker does whatever has been attached to its DoWork event. Below is a simple example of how this might work for you.

private void ShowProgressFormWhileBackgroundWorkerRuns() {
    // this is your presumably long-running method
    Action<string, string> exec = DoSomethingLongAndNotReturnAnyNotification;

    ProgressForm p = new ProgressForm(this);

    BackgroundWorker b = new BackgroundWorker();

    // set the worker to call your long-running method
    b.DoWork += (object sender, DoWorkEventArgs e) => {
        exec.Invoke(path, parameters);
    };

    // set the worker to close your progress form when it's completed
    b.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => {
        if (p != null && p.Visible) p.Close();
    };

    // now actually show the form
    p.Show();

    // this only tells your BackgroundWorker to START working;
    // the current (i.e., GUI) thread will immediately continue,
    // which means your progress bar will update, the window
    // will continue firing button click events and all that
    // good stuff
    b.RunWorkerAsync();
}

3. You can't run two methods at the same time on the same thread

You say this:

I just need to call
Application.DoEvents() so that the
Marque progress bar will work, while
the worker function works in the Main
thread . . .

What you're asking for is simply not real. The "main" thread for a Windows Forms application is the GUI thread, which, if it's busy with your long-running method, is not providing visual updates. If you believe otherwise, I suspect you misunderstand what BeginInvoke does: it launches a delegate on a separate thread. In fact, the example code you have included in your question to call Application.DoEvents between exec.BeginInvoke and exec.EndInvoke is redundant; you are actually calling Application.DoEvents repeatedly from the GUI thread, which would be updating anyway. (If you found otherwise, I suspect it's because you called exec.EndInvoke right away, which blocked the current thread until the method finished.)

So yes, the answer you're looking for is to use a BackgroundWorker.

You could use BeginInvoke, but instead of calling EndInvoke from the GUI thread (which will block it if the method isn't finished), pass an AsyncCallback parameter to your BeginInvoke call (instead of just passing null), and close the progress form in your callback. Be aware, however, that if you do that, you're going to have to invoke the method that closes the progress form from the GUI thread, since otherwise you'll be trying to close a form, which is a GUI function, from a non-GUI thread. But really, all the pitfalls of using BeginInvoke/EndInvoke have already been dealt with for you with the BackgroundWorker class, even if you think it's ".NET magic code" (to me, it's just an intuitive and useful tool).

傲性难收 2024-08-22 18:32:42

对我来说,最简单的方法肯定是使用 BackgroundWorker,它是专门为此类任务设计的。 ProgressChanged 事件非常适合更新进度条,而无需担心跨线程调用

For me the easiest way is definitely to use a BackgroundWorker, which is specifically designed for this kind of task. The ProgressChanged event is perfectly fitted to update a progress bar, without worrying about cross-thread calls

善良天后 2024-08-22 18:32:42

Stackoverflow 上有大量有关 .NET/C# 线程的信息,但是清理 Windows 表单线程的文章对我来说,我们的常驻神谕是 Jon Skeet 的 “Windows 窗体中的线程”

整个系列值得阅读,以温习您的知识或从头开始学习。

我很不耐烦,只要给我看一些代码

就“给我看代码”而言,下面是我如何使用 C# 3.5 来做到这一点。该表单包含 4 个控件:

  • 一个文本框、
  • 一个进度条
  • 2 个按钮:“buttonLongTask”和“buttonAnother”

buttonAnother 纯粹是为了演示在计数到 100 任务运行时 UI 不会被阻塞。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void buttonLongTask_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(LongTask);
        thread.IsBackground = true;
        thread.Start();
    }

    private void buttonAnother_Click(object sender, EventArgs e)
    {
        textBox1.Text = "Have you seen this?";
    }

    private void LongTask()
    {
        for (int i = 0; i < 100; i++)
        {
            Update1(i);
            Thread.Sleep(500);
        }
    }

    public void Update1(int i)
    {
        if (InvokeRequired)
        {
            this.BeginInvoke(new Action<int>(Update1), new object[] { i });
            return;
        }

        progressBar1.Value = i;
    }
}

There's a load of information about threading with .NET/C# on Stackoverflow, but the article that cleared up windows forms threading for me was our resident oracle, Jon Skeet's "Threading in Windows Forms".

The whole series is worth reading to brush up on your knowledge or learn from scratch.

I'm impatient, just show me some code

As far as "show me the code" goes, below is how I would do it with C# 3.5. The form contains 4 controls:

  • a textbox
  • a progressbar
  • 2 buttons: "buttonLongTask" and "buttonAnother"

buttonAnother is there purely to demonstrate that the UI isn't blocked while the count-to-100 task is running.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void buttonLongTask_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(LongTask);
        thread.IsBackground = true;
        thread.Start();
    }

    private void buttonAnother_Click(object sender, EventArgs e)
    {
        textBox1.Text = "Have you seen this?";
    }

    private void LongTask()
    {
        for (int i = 0; i < 100; i++)
        {
            Update1(i);
            Thread.Sleep(500);
        }
    }

    public void Update1(int i)
    {
        if (InvokeRequired)
        {
            this.BeginInvoke(new Action<int>(Update1), new object[] { i });
            return;
        }

        progressBar1.Value = i;
    }
}
简单气质女生网名 2024-08-22 18:32:42

还有另一个例子,BackgroundWorker 是正确的方法......

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace SerialSample
{
    public partial class Form1 : Form
    {
        private BackgroundWorker _BackgroundWorker;
        private Random _Random;

        public Form1()
        {
            InitializeComponent();
            _ProgressBar.Style = ProgressBarStyle.Marquee;
            _ProgressBar.Visible = false;
            _Random = new Random();

            InitializeBackgroundWorker();
        }

        private void InitializeBackgroundWorker()
        {
            _BackgroundWorker = new BackgroundWorker();
            _BackgroundWorker.WorkerReportsProgress = true;

            _BackgroundWorker.DoWork += (sender, e) => ((MethodInvoker)e.Argument).Invoke();
            _BackgroundWorker.ProgressChanged += (sender, e) =>
                {
                    _ProgressBar.Style = ProgressBarStyle.Continuous;
                    _ProgressBar.Value = e.ProgressPercentage;
                };
            _BackgroundWorker.RunWorkerCompleted += (sender, e) =>
            {
                if (_ProgressBar.Style == ProgressBarStyle.Marquee)
                {
                    _ProgressBar.Visible = false;
                }
            };
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            _BackgroundWorker.RunWorkerAsync(new MethodInvoker(() =>
                {
                    _ProgressBar.BeginInvoke(new MethodInvoker(() => _ProgressBar.Visible = true));
                    for (int i = 0; i < 1000; i++)
                    {
                        Thread.Sleep(10);
                        _BackgroundWorker.ReportProgress(i / 10);
                    }
                }));
        }
    }
}

And another example that BackgroundWorker is the right way to do it...

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace SerialSample
{
    public partial class Form1 : Form
    {
        private BackgroundWorker _BackgroundWorker;
        private Random _Random;

        public Form1()
        {
            InitializeComponent();
            _ProgressBar.Style = ProgressBarStyle.Marquee;
            _ProgressBar.Visible = false;
            _Random = new Random();

            InitializeBackgroundWorker();
        }

        private void InitializeBackgroundWorker()
        {
            _BackgroundWorker = new BackgroundWorker();
            _BackgroundWorker.WorkerReportsProgress = true;

            _BackgroundWorker.DoWork += (sender, e) => ((MethodInvoker)e.Argument).Invoke();
            _BackgroundWorker.ProgressChanged += (sender, e) =>
                {
                    _ProgressBar.Style = ProgressBarStyle.Continuous;
                    _ProgressBar.Value = e.ProgressPercentage;
                };
            _BackgroundWorker.RunWorkerCompleted += (sender, e) =>
            {
                if (_ProgressBar.Style == ProgressBarStyle.Marquee)
                {
                    _ProgressBar.Visible = false;
                }
            };
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            _BackgroundWorker.RunWorkerAsync(new MethodInvoker(() =>
                {
                    _ProgressBar.BeginInvoke(new MethodInvoker(() => _ProgressBar.Visible = true));
                    for (int i = 0; i < 1000; i++)
                    {
                        Thread.Sleep(10);
                        _BackgroundWorker.ReportProgress(i / 10);
                    }
                }));
        }
    }
}
守望孤独 2024-08-22 18:32:42

事实上,你走在正确的轨道上。您应该使用另一个线程,并且您已经确定了执行此操作的最佳方法。剩下的就是更新进度条了。如果您不想像其他人建议的那样使用BackgroundWorker,请记住一个技巧。诀窍是您无法从工作线程更新进度条,因为只能从 UI 线程操作 UI。所以你使用 Invoke 方法。它是这样的(自己修复语法错误,我只是写一个简单的例子):

class MyForm: Form
{
    private void delegate UpdateDelegate(int Progress);

    private void UpdateProgress(int Progress)
    {
        if ( this.InvokeRequired )
            this.Invoke((UpdateDelegate)UpdateProgress, Progress);
        else
            this.MyProgressBar.Progress = Progress;
    }
}

InvokeRequired 属性将在除拥有该线程的线程之外的每个线程上返回 true形式。 Invoke 方法将调用 UI 线程上的方法,并会阻塞直至完成。如果您不想阻塞,可以调用 BeginInvoke 来代替。

Indeed you are on the right track. You should use another thread, and you have identified the best ways to do that. The rest is just updating the progress bar. In case you don't want to use BackgroundWorker like others have suggested, there is one trick to keep in mind. The trick is that you cannot update the progress bar from the worker thread because UI can be only manipulated from the UI thread. So you use the Invoke method. It goes something like this (fix the syntax errors yourself, I'm just writing a quick example):

class MyForm: Form
{
    private void delegate UpdateDelegate(int Progress);

    private void UpdateProgress(int Progress)
    {
        if ( this.InvokeRequired )
            this.Invoke((UpdateDelegate)UpdateProgress, Progress);
        else
            this.MyProgressBar.Progress = Progress;
    }
}

The InvokeRequired property will return true on every thread except the one that owns the form. The Invoke method will call the method on the UI thread, and will block until it completes. If you don't want to block, you can call BeginInvoke instead.

情仇皆在手 2024-08-22 18:32:42

BackgroundWorker 不是答案,因为我可能没有收到进度通知...

您没有收到进度通知这一事实到底与使用 <代码>后台工作人员?如果您的长时间运行的任务没有可靠的机制来报告其进度,则无法可靠地报告其进度。

报告长时间运行的方法的进度的最简单方法是在 UI 线程上运行该方法,并通过更新进度条然后调用 Application.DoEvents() 来报告进度。从技术上讲,这将起作用。但在调用 Application.DoEvents() 之间,UI 将无响应。这是一种快速而肮脏的解决方案,正如史蒂夫·麦康奈尔(Steve McConnell)所观察到的,快速而肮脏的解决方案的问题在于,在快速的甜味被遗忘之后,肮脏的苦味仍然存在很长时间。

正如另一张海报所提到的,下一个最简单的方法是实现一个模式表单,该表单使用 BackgroundWorker 来执行长时间运行的方法。这提供了总体上更好的用户体验,并且使您不必解决潜在的复杂问题,即在执行长时间运行的任务时,UI 的哪些部分保持功能状态 - 当模态表单打开时,其余部分都不会运行。您的 UI 将响应用户操作。这是快速而干净的解决方案。

但它仍然对用户充满敌意。当长时间运行的任务正在执行时,它仍然会锁定 UI;它只是以一种漂亮的方式做到了。为了制定一个用户友好的解决方案,您需要在另一个线程上执行任务。最简单的方法是使用 BackgroundWorker

这种方法为许多问题打开了大门。它不会“泄漏”,无论这意味着什么。但无论长时间运行的方法在做什么,它现在都必须与运行时保持启用状态的 UI 部分完全隔离。我所说的完整是指完整。如果用户可以用鼠标单击任意位置并导致对长时间运行的方法所查看的某些对象进行一些更新,那么您就会遇到问题。长时间运行的方法使用的任何可能引发事件的对象都可能导致痛苦。

正是如此,并且无法让 BackgroundWorker 正常工作,这将是所有痛苦的根源。

BackgroundWorker is not the answer because it may be that I don't get the progress notification...

What on earth does the fact that you're not getting progress notification have to do with the use of BackgroundWorker? If your long-running task doesn't have a reliable mechanism for reporting its progress, there's no way to reliably report its progress.

The simplest possible way to report progress of a long-running method is to run the method on the UI thread and have it report progress by updating the progress bar and then calling Application.DoEvents(). This will, technically, work. But the UI will be unresponsive between calls to Application.DoEvents(). This is the quick and dirty solution, and as Steve McConnell observes, the problem with quick and dirty solutions is that the bitterness of the dirty remains long after the sweetness of the quick is forgotten.

The next simplest way, as alluded to by another poster, is to implement a modal form that uses a BackgroundWorker to execute the long-running method. This provides a generally better user experience, and it frees you from having to solve the potentially complicated problem of what parts of your UI to leave functional while the long-running task is executing - while the modal form is open, none of the rest of your UI will respond to user actions. This is the quick and clean solution.

But it's still pretty user-hostile. It still locks up the UI while the long-running task is executing; it just does it in a pretty way. To make a user-friendly solution, you need to execute the task on another thread. The easiest way to do that is with a BackgroundWorker.

This approach opens the door to a lot of problems. It won't "leak," whatever that is supposed to mean. But whatever the long-running method is doing, it now has to do it in complete isolation from the pieces of the UI that remain enabled while it's running. And by complete, I mean complete. If the user can click anywhere with a mouse and cause some update to be made to some object that your long-running method ever looks at, you'll have problems. Any object that your long-running method uses which can raise an event is a potential road to misery.

It's that, and not getting BackgroundWorker to work properly, that's going to be the source of all of the pain.

动次打次papapa 2024-08-22 18:32:42

我必须给出最简单的答案。您始终可以只实现进度条,而与任何实际进度无关。只需开始填充栏,例如每秒 1% 或每秒 10%,无论是否与您的操作类似,如果它填满则重新开始。

这至少会给用户一种正在处理的感觉,让他们明白要等待,而不是仅仅单击一个按钮,然后看到什么也没有发生,然后再单击它。

I have to throw the simplest answer out there. You could always just implement the progress bar and have no relationship to anything of actual progress. Just start filling the bar say 1% a second, or 10% a second whatever seems similar to your action and if it fills over to start again.

This will atleast give the user the appearance of processing and make them understand to wait instead of just clicking a button and seeing nothing happen then clicking it more.

奈何桥上唱咆哮 2024-08-22 18:32:42

这是另一个使用 BackgroundWorker 更新 ProgressBar 的示例代码,只需将 BackgroundWorkerProgressbar 添加到主窗体中,然后使用以下代码:

public partial class Form1 : Form
{
    public Form1()
    {
      InitializeComponent();
      Shown += new EventHandler(Form1_Shown);

    // To report progress from the background worker we need to set this property
    backgroundWorker1.WorkerReportsProgress = true;
    // This event will be raised on the worker thread when the worker starts
    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    // This event will be raised when we call ReportProgress
    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
    // Start the background worker
    backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Your background task goes here
    for (int i = 0; i <= 100; i++)
    {
        // Report progress to 'UI' thread
        backgroundWorker1.ReportProgress(i);
        // Simulate long task
        System.Threading.Thread.Sleep(100);
    }
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // The progress percentage is a property of e
    progressBar1.Value = e.ProgressPercentage;
}
}

refrence:来自codeproject

Here is another sample code to use BackgroundWorker to update ProgressBar, just add BackgroundWorker and Progressbar to your main form and use below code:

public partial class Form1 : Form
{
    public Form1()
    {
      InitializeComponent();
      Shown += new EventHandler(Form1_Shown);

    // To report progress from the background worker we need to set this property
    backgroundWorker1.WorkerReportsProgress = true;
    // This event will be raised on the worker thread when the worker starts
    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    // This event will be raised when we call ReportProgress
    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
    // Start the background worker
    backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Your background task goes here
    for (int i = 0; i <= 100; i++)
    {
        // Report progress to 'UI' thread
        backgroundWorker1.ReportProgress(i);
        // Simulate long task
        System.Threading.Thread.Sleep(100);
    }
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // The progress percentage is a property of e
    progressBar1.Value = e.ProgressPercentage;
}
}

refrence:from codeproject

岛徒 2024-08-22 18:32:42

使用BackgroundWorker 组件,它正是针对这种情况而设计的。

您可以挂钩其进度更新事件并更新进度栏。 BackgroundWorker 类确保回调被编组到 UI 线程,因此您也无需担心任何细节。

Use the BackgroundWorker component it is designed for exactly this scenario.

You can hook into its progress update events and update your progress bar. The BackgroundWorker class ensures the callbacks are marshalled to the UI thread so you don't need to worry about any of that detail either.

拥醉 2024-08-22 18:32:42

阅读您的需求的最简单方法是显示无模式表单并使用标准 System.Windows.Forms 计时器来更新无模式表单上的进度。没有线程,没有可能的内存泄漏。

由于这仅使用一个 UI 线程,因此您还需要在主处理期间的某些时刻调用 Application.DoEvents() 以确保进度条在视觉上更新。

Reading your requirements the simplest way would be to display a mode-less form and use a standard System.Windows.Forms timer to update the progress on the mode-less form. No threads, no possible memory leaks.

As this only uses the one UI thread, you would also need to call Application.DoEvents() at certain points during your main processing to guarantee the progress bar is updated visually.

〆凄凉。 2024-08-22 18:32:42

回复:您的编辑。
您需要一个BackgroundWorker 或Thread 来完成这项工作,但它必须定期调用ReportProgress() 来告诉UI 线程它正在做什么。 DotNet 无法神奇地算出你已经完成了多少工作,所以你必须告诉它 (a) 你将达到的最大进度量是多少,然后 (b) 在这个过程中大约 100 次左右,告诉它您能达到的金额。 (如果您报告进度少于 100 次,进度条将大幅跳跃。如果您报告超过 100 次,您只是在浪费时间尝试报告进度条无法帮助显示的更详细的细节)

如果您的 UI当后台工作程序运行时,线程可以愉快地继续,然后您的工作就完成了。

然而,实际上,在大多数需要运行进度指示的情况下,您的 UI 需要非常小心,以避免重入调用。例如,如果您在导出数据时运行进度显示,则您不希望用户在导出过程中再次开始导出数据。

您可以通过两种方式处理此问题:

  • 导出操作检查后台工作程序是否正在运行,并在导入时禁用导出选项。这将允许用户在程序中执行除导出之外的任何操作 - 如果用户可以(例如)编辑正在导出的数据,这仍然可能很危险。

  • 将进度条作为“模态”显示运行,以便您的程序在导出过程中保持“活动”状态,但在导出完成之前用户实际上无法执行任何操作(除了取消之外)。 DotNet 在支持这一点上是垃圾,尽管它是最常见的方法。在这种情况下,您需要将 UI 线程置于繁忙的等待循环中,在该循环中调用 Application.DoEvents() 来保持消息处理运行(以便进度条正常工作),但您需要添加一个仅允许您的应用程序的 MessageFilter响应“安全”事件(例如,它将允许 Paint 事件,以便您的应用程序窗口继续重绘,但它会过滤掉鼠标和键盘消息,以便用户在导出过程中实际上无法在程序中执行任何操作您还需要传递一些偷偷摸摸的消息才能让窗口正常工作,弄清楚这些消息将需要几分钟 - 我在工作中有一个它们的列表,但没有它们。恐怕这是所有显而易见的东西,比如 NCHITTEST 加上一个偷偷摸摸的 .net 东西(在 WM_USER 范围内是邪恶的),这对于使其正常工作至关重要)。

糟糕的 dotNet 进度条的最后一个“问题”是,当您完成操作并关闭进度条时,您会发现它通常在报告“80%”之类的值时退出。即使你强行调到100%,然后等待半秒左右,也可能达不到100%。啊啊!解决方案是将进度设置为 100%,然后设置为 99%,然后返回到 100% - 当进度条被告知向前移动时,它会缓慢地向目标值移动。但如果你告诉它“向后”走,它会立即跳到那个位置。因此,通过在最后暂时反转它,您可以让它实际显示您要求其显示的值。

Re: Your edit.
You need a BackgroundWorker or Thread to do the work, but it must call ReportProgress() periodically to tell the UI thread what it is doing. DotNet can't magically work out how much of the work you have done, so you have to tell it (a) what the maximum progress amount you will reach is, and then (b) about 100 or so times during the process, tell it which amount you are up to. (If you report progress fewer than 100 times, the progess bar will jump in large steps. If you report more than 100 times, you will just be wasting time trying to report a finer detail than the progress bar will helpfully display)

If your UI thread can happily continue while the background worker is running, then your work is done.

However, realistically, in most situations where the progress indication needs to be running, your UI needs to be very careful to avoid a re-entrant call. e.g. If you are running a progress display while exporting data, you don't want to allow the user to start exporting data again while the export is in progress.

You can handle this in two ways:

  • The export operation checks to see if the background worker is running, and disabled the export option while it is already importing. This will allow the user to do anything at all in your program except exporting - this could still be dangerous if the user could (for example) edit the data that is being exported.

  • Run the progress bar as a "modal" display so that your program reamins "alive" during the export, but the user can't actually do anything (other than cancel) until the export completes. DotNet is rubbish at supporting this, even though it's the most common approach. In this case, you need to put the UI thread into a busy wait loop where it calls Application.DoEvents() to keep message handling running (so the progress bar will work), but you need to add a MessageFilter that only allows your application to respond to "safe" events (e.g. it would allow Paint events so your application windows continue to redraw, but it would filter out mouse and keyboard messages so that the user can't actually do anything in the proigram while the export is in progress. There are also a couple of sneaky messages you'll need to pass through to allow the window to work as normal, and figuring these out will take a few minutes - I have a list of them at work, but don't have them to hand here I'm afraid. It's all the obvious ones like NCHITTEST plus a sneaky .net one (evilly in the WM_USER range) which is vital to get this working).

The last "gotcha" with the awful dotNet progress bar is that when you finish your operation and close the progress bar you'll find that it usually exits when reporting a value like "80%". Even if you force it to 100% and then wait for about half a second, it still may not reach 100%. Arrrgh! The solution is to set the progress to 100%, then to 99%, and then back to 100% - when the progress bar is told to move forwards, it animates slowly towards the target value. But if you tell it to go "backwards", it jumps immediately to that position. So by reversing it momentarily at the end, you can get it to actually show the value you asked it to show.

合约呢 2024-08-22 18:32:42

如果您想要一个“旋转”进度条,为什么不将进度条样式设置为“Marquee”并使用 BackgroundWorker 来保持 UI 响应?没有比使用“Marquee”风格更容易实现旋转进度条的了...

If you want a "rotating" progress bar, why not set the progress bar style to "Marquee" and using a BackgroundWorker to keep the UI responsive? You won't achieve a rotating progress bar easier than using the "Marquee" - style...

梦巷 2024-08-22 18:32:42

我们使用带有 BackgroundWorker 的模态形式来完成这样的事情。

这是快速解决方案:

  public class ProgressWorker<TArgument> : BackgroundWorker where TArgument : class 
    {
        public Action<TArgument> Action { get; set; }

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            if (Action!=null)
            {
                Action(e.Argument as TArgument);
            }
        }
    }


public sealed partial class ProgressDlg<TArgument> : Form where TArgument : class
{
    private readonly Action<TArgument> action;

    public Exception Error { get; set; }

    public ProgressDlg(Action<TArgument> action)
    {
        if (action == null) throw new ArgumentNullException("action");
        this.action = action;
        //InitializeComponent();
        //MaximumSize = Size;
        MaximizeBox = false;
        Closing += new System.ComponentModel.CancelEventHandler(ProgressDlg_Closing);
    }
    public string NotificationText
    {
        set
        {
            if (value!=null)
            {
                Invoke(new Action<string>(s => Text = value));  
            }

        }
    }
    void ProgressDlg_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        FormClosingEventArgs args = (FormClosingEventArgs)e;
        if (args.CloseReason == CloseReason.UserClosing)
        {
            e.Cancel = true;
        }
    }



    private void ProgressDlg_Load(object sender, EventArgs e)
    {

    }

    public void RunWorker(TArgument argument)
    {
        System.Windows.Forms.Application.DoEvents();
        using (var worker = new ProgressWorker<TArgument> {Action = action})
        {
            worker.RunWorkerAsync();
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;                
            ShowDialog();
        }
    }

    void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            Error = e.Error;
            DialogResult = DialogResult.Abort;
            return;
        }

        DialogResult = DialogResult.OK;
    }
}

以及我们如何使用它:

var dlg = new ProgressDlg<string>(obj =>
                                  {
                                     //DoWork()
                                     Thread.Sleep(10000);
                                     MessageBox.Show("Background task completed "obj);
                                   });
dlg.RunWorker("SampleValue");
if (dlg.Error != null)
{
  MessageBox.Show(dlg.Error.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
dlg.Dispose();

We are use modal form with BackgroundWorker for such a thing.

Here is quick solution:

  public class ProgressWorker<TArgument> : BackgroundWorker where TArgument : class 
    {
        public Action<TArgument> Action { get; set; }

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            if (Action!=null)
            {
                Action(e.Argument as TArgument);
            }
        }
    }


public sealed partial class ProgressDlg<TArgument> : Form where TArgument : class
{
    private readonly Action<TArgument> action;

    public Exception Error { get; set; }

    public ProgressDlg(Action<TArgument> action)
    {
        if (action == null) throw new ArgumentNullException("action");
        this.action = action;
        //InitializeComponent();
        //MaximumSize = Size;
        MaximizeBox = false;
        Closing += new System.ComponentModel.CancelEventHandler(ProgressDlg_Closing);
    }
    public string NotificationText
    {
        set
        {
            if (value!=null)
            {
                Invoke(new Action<string>(s => Text = value));  
            }

        }
    }
    void ProgressDlg_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        FormClosingEventArgs args = (FormClosingEventArgs)e;
        if (args.CloseReason == CloseReason.UserClosing)
        {
            e.Cancel = true;
        }
    }



    private void ProgressDlg_Load(object sender, EventArgs e)
    {

    }

    public void RunWorker(TArgument argument)
    {
        System.Windows.Forms.Application.DoEvents();
        using (var worker = new ProgressWorker<TArgument> {Action = action})
        {
            worker.RunWorkerAsync();
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;                
            ShowDialog();
        }
    }

    void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            Error = e.Error;
            DialogResult = DialogResult.Abort;
            return;
        }

        DialogResult = DialogResult.OK;
    }
}

And how we use it:

var dlg = new ProgressDlg<string>(obj =>
                                  {
                                     //DoWork()
                                     Thread.Sleep(10000);
                                     MessageBox.Show("Background task completed "obj);
                                   });
dlg.RunWorker("SampleValue");
if (dlg.Error != null)
{
  MessageBox.Show(dlg.Error.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
dlg.Dispose();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文