我的按钮单击事件中有一个相当重的循环,大约需要 1-2 分钟才能完成(循环大约 50000 次):
while (continue)
{
if (xlRange.Cells[i, j].Value2 == null)
continue = false;
else
{
pbar.PerformStep();
string key = xlRange.Cells[i, j].Value2.ToString();
Random r = new Random();
bool ok = r.Next(100) <= 2 ? false : true;
if (!ok)
{
this.dataGridView1.Rows.Add(x + 1, key);
x++;
groupBox2.Text = "Error (" + x + ")";
}
i++;
}
}
该循环锁定了 UI,无法按任何按钮,甚至无法移动窗口。
我怎样才能以“专业”方式异步或不阻塞?谢谢。
使用线程怎么样?
new Thread(() =>
{
while (continue)
{
if (xlRange.Cells[i, j].Value2 == null)
continue = false;
else
{
Invoke(new Action(() =>
{
pbar.PerformStep();
}));
string key = xlRange.Cells[i, j].Value2.ToString();
Random r = new Random();
bool ok = r.Next(100) <= 2 ? false : true;
if (!ok)
{
Invoke(new Action(() =>
{
this.dataGridView1.Rows.Add(x + 1, key);
}));
x++;
Invoke(new Action(() =>
{
groupBox2.Text = "Error (" + x + ")";
}));
}
i++;
}
}
}).Start();
此代码阻止异常“跨线程操作无效”
Invoke(new Action(() =>
{
// Form modification code
}));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)