Display progress bar while doing some work in C#?

后端 未结 13 1810
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 12:07

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 Pro

相关标签:
13条回答
  • 2020-11-27 13:03

    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();
    
    0 讨论(0)
  • 2020-11-27 13:04

    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

    0 讨论(0)
  • 2020-11-27 13:07

    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);
                        }
                    }));
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:08

    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.

    0 讨论(0)
  • 2020-11-27 13:10

    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.

    0 讨论(0)
  • 2020-11-27 13:12

    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.

    0 讨论(0)
提交回复
热议问题