在.Net Windows窗体中循环时不阻止UI [英] Not block UI while loop in .Net Windows Forms

查看:54
本文介绍了在.Net Windows窗体中循环时不阻止UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的按钮单击事件中有一个非常沉重的循环,大约需要1-2分钟才能完成(循环大约5万次):

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++;
    }
}

该循环锁定了UI,无法按下任何按钮甚至无法移动窗口.

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.

推荐答案

如何使用线程?

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
}));

这篇关于在.Net Windows窗体中循环时不阻止UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆