【问题标题】:Background worker "cause" to freeze my form后台工作人员“导致”冻结我的表格
【发布时间】:2012-05-25 05:45:31
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net winforms backgroundworker


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多