C# Progressbar value in foreach()

2019-09-08 04:50发布

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?

3条回答
一纸荒年 Trace。
2楼-- · 2019-09-08 05:12

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();
});
查看更多
Anthone
3楼-- · 2019-09-08 05:25

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

查看更多
冷血范
4楼-- · 2019-09-08 05:28

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.

查看更多
登录 后发表回答