帮助我使用CrossThread?

Pok*_*kus 0 .net c# multithreading winforms

此代码以多种方式执行.当它由表单按钮执行时它工作(按钮启动一个线程,在循环中它调用这个方法=它工作).但是当我从表单中的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
}
Run Code Online (Sandbox Code Playgroud)

然后在包含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.
Run Code Online (Sandbox Code Playgroud)

为什么?

Jon*_*eet 6

你需要在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
}
Run Code Online (Sandbox Code Playgroud)

或者只是将方法的后半部分放在"else"块中.