Not block UI while loop in .Net Windows Forms

六月ゝ 毕业季﹏ 提交于 2020-12-25 05:42:08

问题


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

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