C# Progressbar value in foreach()

2019-09-08 04:30发布

问题:

I have this code:

 private void button1_Click(object sender, EventArgs e)
    {
        var max = 0;
        foreach (var address in textBox2.Text.Split(','))
        {
            max = +1;
        }
        var maxp = 100 / max;
        foreach (var address in textBox2.Text.Split(','))
        {
            SendMessage(address);
            progressBar1.Value = +maxp;
        }
    }

It calculates how many emails are in the textbox, and then makes a proportion. To each email sent adds the value of progress, the problem is that when I press the button, the progressbar does not move. When all emails are sent the progressbar moves to the end of stroke. How can I do?

回答1:

This happens because you loop and the ui are executing on the same thread. While the loop is busy, it can't update the ui

You can use a BackgroundWorker to run the loop on a different thread in the background, then use the BackgroundWorker's ProgressChanged event to update your progressbar. You can learn more about BackgroundWorkers here



回答2:

Again you are executing code on a thread other than the UI thread. In WinForms you must invoke back to the UI thread and in WPF you must use application dispatcher.

WinForms:

Invoke((MethodInvoker) delegate {
    DoSomethingOnUiThread();
});

WPF:

Application.Current.Dispatcher.Invoke(() =>{
  DoSomethingOnUiThread();
});


回答3:

You block the UI thread so it cannot refresh the UI until the processing leaves the method.

See three different solutions here with explicitly used threads, BackgroundWorker and async-await techniques.