问题
I have a pretty heavy loop in my button click event that takes about 1-2 minutes to complete (loops around 50000 times):
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++;
}
}
The loop locks the UI and it is not possible to press any button or even move the window.
How can I do this asynchronous or not blocking in a 'pro' way? Thanks.
回答1:
How about using the thread?
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();
This code blocks the exception "Cross-thread operation not valid"
Invoke(new Action(() =>
{
// Form modification code
}));
回答2:
I think Application.DoEvents();
will let you work with the UI, however this might slow it down a little.
来源:https://stackoverflow.com/questions/57161427/not-block-ui-while-loop-in-net-windows-forms