后台工作人员“导致”冻结我的表格

时间:2012-05-17 16:03:45

标签: c# .net winforms backgroundworker

在我的应用程序中,我想在后台创建数千个文件,但是当我执行它时,它总是冻结我的表单(在创建所有文件后我可以再次使用我的表单)。如何正常运行而不挂?

private void button5_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();

        bw.WorkerReportsProgress = true;

        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            this.Invoke(new MethodInvoker(delegate
            {
                getValues();//load some text fields into strings

                while (counter < counted)
                {
                    text = richTextBox1.Text;
                    text = text.Replace("number", finalNumber);

                    //create copies
                    if (checkBox1.Checked == true)
                    {
                        while (createdCopies < copies)
                        {
                            createdCopies++;

                            File.WriteAllText(fileName, text);
                            overalCounter++;
                            b.ReportProgress(overalCounter);
                        }
                        counter++;
                        createdCopies = 0;
                    }
                    //dont create copies
                    else
                    {
                        File.WriteAllText(fileName, text);
                        counter++;
                        overalCounter++;
                        b.ReportProgress(overalCounter);
                    }
                    //info about number of files created
                    label6.Text = "created " + overalCounter.ToString() + " files";

                }
                label1.Text = "success";
            }));
    });

    if (bw.IsBusy != true)
    {
        bw.RunWorkerAsync();
    }

    bw.ProgressChanged += new ProgressChangedEventHandler(
    delegate(object o, ProgressChangedEventArgs args)
    {
        this.Text = string.Format("{0}% Completed", args.ProgressPercentage);
    });
    }

2 个答案:

答案 0 :(得分:3)

this.Invoke在UI线程中运行代码,阻止任何UI更新 由于您在Invoke方法中运行所有内容,因此所有内容都将在UI线程上运行。

在您修改UI控件的每个位置周围创建一个单独的Invoke,并将繁重的工作留在Invoke之外。

答案 1 :(得分:0)

在第一个代表中完成实际工作。第二个委托this.Invoke(...)在表单的线程(=主线程)上执行,因此会阻止UI。