26

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

我有一个 WinForm ProgressForm ,ProgressBar它会以字幕方式无限期地继续下去。

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

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

我对 EndInvoke 有一些问题,尽管这不是问题所在。问题是哪种是处理此类情况的最佳和最简单的方法,您必须向用户展示程序正在运行且不会无响应,以及如何使用最简单的代码来处理它,该代码可能高效且成功' t 泄漏,并且可以更新 GUI。

比如BackgroundWorker需要有多个函数,声明成员变量等。你还需要持有对 ProgressBar 表单的引用并处理它。

编辑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);

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

4

13 回答 13

44

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

1. 无需引发 ProgressChanged 事件即可拥有响应式 UI

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

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

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

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

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

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

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

这在多线程场景中是不正确的;如果您使用 a 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 进度条可以工作,而辅助函数在主线程中工作。. .

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

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

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

于 2009-12-30T02:31:53.013 回答
16

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

于 2009-12-23T11:27:52.120 回答
11

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

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

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

至于“给我看代码”,下面是我如何使用 C# 3.5 来做的。该表单包含 4 个控件:

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

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;
    }
}
于 2009-12-23T12:09:52.460 回答
9

另一个例子是 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);
                    }
                }));
        }
    }
}
于 2009-12-28T15:17:02.547 回答
3

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.

于 2009-12-23T11:32:02.037 回答
2

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

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

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

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

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

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

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

于 2009-12-28T19:33:41.203 回答
1

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

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

于 2009-12-28T19:04:03.590 回答
1

这是另一个BackgroundWorker用于更新的示例代码ProgressBar,只需将BackgroundWorker和添加Progressbar到您的主表单并使用以下代码:

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;
}
}

参考:来自代码项目

于 2016-07-27T16:18:44.917 回答
0

回复:您的编辑。您需要一个 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% - 当进度条被告知向前移动时,它会向目标值缓慢移动。但是如果你告诉它“向后”,它会立即跳到那个位置。因此,通过在最后暂时反转它,您可以让它实际显示您要求它显示的值。

于 2009-12-28T18:50:04.863 回答
0

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();
于 2009-12-23T11:30:20.027 回答
0

使用专为这种情况设计的 BackgroundWorker 组件。

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

于 2009-12-23T11:27:05.400 回答
0

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

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

于 2009-12-23T11:35:17.877 回答
0

如果您想要一个“旋转”进度条,为什么不将进度条样式设置为“Marquee”并使用 aBackgroundWorker来保持 UI 响应?你不会比使用“选框”更容易实现旋转进度条 - 样式......

于 2009-12-30T12:31:24.640 回答