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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1952201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:10:24  来源:igfitidea点击:

Display progress bar while doing some work in C#?

c#multithreading.net-3.5begininvoke

提问by Priyank Bolia

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

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

I have a WinForm ProgressForm with a ProgressBarthat will continue indefinitely in a marqueefashion.

我有一个 WinForm ProgressForm ProgressBar,它将无限期地以选框方式继续。

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 BackgroundWorkeror Threads.

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

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.

我对 EndInvoke 有一些问题,尽管这不是问题。问题是你用来处理这种情况的最好和最简单的方法是什么,你必须向用户展示程序正在运行而不是没有响应,以及你如何用最简单的代码来处理这种情况,既高效又成功” t 泄漏,并且可以更新 GUI。

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

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

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

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

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 :

赏金是针对此问题的最佳代码解决方案。我只需要调用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);

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

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

采纳答案by Dan Tao

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

1. 无需引发 ProgressChanged 事件即可拥有响应式 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 . . .

BackgroundWorker 不是答案,因为我可能没有收到进度通知,这意味着不会调用 ProgressChanged,因为 DoWork 是对外部函数的单个调用。. .

Actually, it does not matter whether you call the ProgressChangedevent 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 ProgressChangedevent at all. The progress bar will continue rotating as long as it is displayed because the BackgroundWorkeris doing its work on a separate thread from the GUI.

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

(On a side note, DoWorkis 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.)

(附带说明,DoWork是一个事件,这意味着它不仅仅是“对外部函数的一次调用”;您可以添加任意数量的处理程序;并且每个处理程序都可以包含尽可能多的函数调用喜欢。)

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

2. 无需调用 Application.DoEvents 即可拥有响应式 UI

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

对我来说,听起来您认为更新 GUI的唯一方法是调用Application.DoEvents

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

我需要继续调用 Application.DoEvents(); 使进度条保持旋转。

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 BackgroundWorkerdoes whatever has been attached to its DoWorkevent. Below is a simple example of how this might work for you.

这在多线程场景中并非如此;如果您使用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. You can't run two methods at the same time on the same thread

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

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 . . .

我只需要调用 Application.DoEvents() 以便 Marque 进度条可以工作,而辅助函数在 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 BeginInvokedoes: it launches a delegate on a separate thread. In fact, the example code you have included in your question to call Application.DoEventsbetween exec.BeginInvokeand exec.EndInvokeis redundant; you are actually calling Application.DoEventsrepeatedly from the GUI thread, which would be updating anyway. (If you found otherwise, I suspect it's because you called exec.EndInvokeright away, which blocked the current thread until the method finished.)

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

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

所以是的,您正在寻找的答案是使用BackgroundWorker.

You coulduse BeginInvoke, but instead of calling EndInvokefrom the GUI thread (which will block it if the method isn't finished), pass an AsyncCallbackparameter to your BeginInvokecall (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/EndInvokehave already been dealt with foryou with the BackgroundWorkerclass, even if you think it's ".NET magic code" (to me, it's just an intuitive and useful tool).

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

回答by Paolo

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

使用专为此场景设计的 BackgroundWorker 组件。

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.

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

回答by Thomas Levesque

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

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

回答by Sergey Mirvoda

We are use modal form with BackgroundWorkerfor such a thing.

BackgroundWorker对于这样的事情,我们使用模态形式 with 。

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();

回答by Vilx-

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):

确实,您走在正确的轨道上。您应该使用另一个线程,并且您已经确定了执行此操作的最佳方法。剩下的就是更新进度条了。如果您不想像其他人建议的那样使用 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;
    }
}

The InvokeRequiredproperty will return trueon every thread except the one that owns the form. The Invokemethod will call the method on the UI thread, and will block until it completes. If you don't want to block, you can call BeginInvokeinstead.

除了拥有表单的线程之外,该InvokeRequired属性将true在每个线程上返回。该Invoke方法将在 UI 线程上调用该方法,并将阻塞直到它完成。如果您不想阻止,则可以调用BeginInvoke

回答by Ash

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.

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

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.

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

回答by Chris S

There's a load of information about threadingwith .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".

Stackoverflow 上有大量关于使用 .NET/C# 进行线程处理的信息,但为我清理 Windows 窗体线程的文章是我们常驻的预言机,Jon Skeet 的“Windows 窗体中线程”

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:

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

  • a textbox
  • a progressbar
  • 2 buttons: "buttonLongTask" and "buttonAnother"
  • 一个文本框
  • 进度条
  • 2 个按钮:“buttonLongTask”和“buttonAnother”

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

buttonAnother是否纯粹是为了证明在 count-to-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;
    }
}

回答by Oliver

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

另一个例子,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);
                    }
                }));
        }
    }
}

回答by Jason Williams

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)

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

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

如果您的 UI 线程可以在后台工作者运行时愉快地继续,那么您的工作就完成了。

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.

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

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).

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

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

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.

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

回答by Chris Marisic

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.

我必须抛出最简单的答案。您始终可以只实现进度条,而与任何实际进度无关。刚开始填充栏说每秒 1%,或每秒 10% 任何看起来与您的操作相似的,如果它填充重新开始。

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.

这至少会给用户一个处理的外观,让他们理解等待,而不是仅仅点击一个按钮然后什么也没有看到然后点击它。

回答by Robert Rossney

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

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

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.

您没有收到进度通知的事实与使用 有BackgroundWorker什么关系?如果您的长时间运行的任务没有可靠的机制来报告其进度,则无法可靠地报告其进度。

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.

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

The next simplest way, as alluded to by another poster, is to implement a modal form that uses a BackgroundWorkerto 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.

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

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.

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

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

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

就是这样,如果不能BackgroundWorker正常工作,这将是所有痛苦的根源。