C# Progressbar value in foreach()

怎甘沉沦 提交于 2020-01-06 15:19:05

问题


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.



来源:https://stackoverflow.com/questions/41504541/c-sharp-progressbar-value-in-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!