我正在执行大量插入操作,我想添加一个进度条。使用Parallel ForEach,我收到以下错误:
“Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException”
progressbar1一个levéuneexception de type'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException
private void button1_Click(object sender, EventArgs e)
{
textBox4.Text = richTextBox1.Lines.Length.ToString();
DateTime start = DateTime.Now;
TimeSpan timediff = new TimeSpan();
progressBar1.Maximum = i;
progressBar1.Minimum = 0;
progressBar1.Step = 1;
int j = 1;
l = 0;
k=0;
Parallel.ForEach(richTextBox1.Lines, (line) =>
{
progressBar1.Value = j;
try
{
string pwd = query.Querie_read("select plain from rainbow where plain='" + line.ToString() + "'");
if (pwd != line.ToString())
{
fct.AddRainbow(line.ToString());
k++;
}
else
{
l++;
}
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
l++;
}
j++;
});
textBox1.Text = k.ToString();
textBox3.Text = l.ToString();
timediff = DateTime.Now.Subtract(start);
textBox2.Text = timediff.ToString();
MessageBox.Show("Finished");
}
答案 0 :(得分:1)
UI只能从主线程(或更准确地说,创建UI的线程)更新。要在正确的线程中执行代码,请使用调度程序:
对于WPF:
this.Dispatcher.BeginInvoke(new Action(() => progressBar1.Value = j));
对于WinForm:
this.BeginInvoke(new Action(() => progressBar1.Value = j));
答案 1 :(得分:0)
progressBar1.Invoke((MethodInvoker)(delegate() { progressBar1.Value = j; }))