Display progress bar while doing some work in C#?

后端 未结 13 1809
佛祖请我去吃肉
佛祖请我去吃肉 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 12:48

    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.

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

    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.

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

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

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

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

    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.

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

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

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