【问题标题】:Help me with that CrossThread?帮我解决那个CrossThread?
【发布时间】:2008-12-03 13:56:12
【问题描述】:

此代码以多种方式执行。当它由表单按钮执行时,它起作用(按钮启动一个线程并在循环中调用此方法=它起作用)。但是当我从表单中的 BackgroundWorker 调用该方法时,它不起作用。

使用以下代码:

private void resizeThreadSafe(int width, int height)
{
    if (this.form.InvokeRequired)
    {
        this.form.Invoke(new DelegateSize(resizeThreadSafe),
            new object[] { width, height });
    }
    this.form.Size = new Size(width, height); // problem occurs on this line
    this.form.Location = new Point(0, 0); // dummy coordinate
}

然后在包含this.form.Size = ... 的行上出现以下异常:

InvalidOperationException was unhandled
Cross-thread operation not valid: Control 'Form1' accessed from a thread other
than the thread it was created on.

为什么?

【问题讨论】:

    标签: c# .net winforms multithreading


    【解决方案1】:

    您需要在 if 块的末尾返回 - 否则您将在正确的线程中调整它的大小,然后在错误的线程中也这样做。

    换句话说(如果你剪切和粘贴代码而不是图片,这会更容易......)

    private void resizeThreadSafe(int width, int height)
    {
        if (this.form.InvokeRequired)
        {
            this.form.Invoke(new DelegateSize(resizeThreadSafe,
                new object[] { width, height });
            return;
        }
        this.form.Size = new Size(width, height);
        this.form.Location = new Point(0, SystemInformation.MonitorSize // whatever comes next
    }
    

    或者,只需将方法的后半部分放在“else”块中。

    【讨论】:

      【解决方案2】:

      你需要这样写:

      if ( this.form.InvokeRequired ) {
          this.form.Invoke( ...... );
          return;
      }
      this.form.Size = new Sizte( ... );
      

      if ( this.form.InvokeRequired ) {
          this.form.Invoke( ...... );
      }
      else {
          this.form.Size = new Sizte( ... );
      }
      

      【讨论】:

        【解决方案3】:

        根据您的编码风格,在 Invoke 之后使用 return 或将实际操作作为 else 块

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-26
          • 1970-01-01
          • 1970-01-01
          • 2019-09-02
          • 1970-01-01
          相关资源
          最近更新 更多