110,534
社区成员
发帖
与我相关
我的任务
分享
private void button1_Click(object sender, EventArgs e)
{
string[] strs = new string[1000];
progressBar1.Value = 0;
progressBar1.Maximum = 1000;
for (int i = 0; i < 1000; i++)
strs[i] = i.ToString();
textBox1.Text = "";
Parallel.ForEach(strs, num =>
{
this.Invoke(new Action(() =>
{
textBox1.Text += num + ";";
textBox1.Refresh();
progressBar1.Value++;
progressBar1.Refresh();
label1.Text = progressBar1.Value + "/" + progressBar1.Maximum;
label1.Refresh();
}));
});
MessageBox.Show("successful");
}
private void button1_Click(object sender, EventArgs e)
{
//界面调整,比如 button1.Enabled = false; 以防止重入
//利用线程池安排一个线程执行并行循环
System.Threading.ThreadPool.QueueUserWorkItem(w =>
{
//非并行部分,比如string[] strs = System.Linq.Enumerable.Range(0, 1000).ToArray();
Parallel.ForEach(strs, num =>
{
//并行部分,比如文件IO
this.Invoke(new Action(() =>
{
//界面更新
}));
});
//并行处理结束,使用Invoke调用MessageBox.Show以显示一个模态窗口
//相应的界面更改也写进Invoke调用里,比如 button1.Enabled = true
this.Invoke(new MethodInvoker(() => MessageBox.Show("successful")));
}, null);
}