帮助我使用CrossThread?

此代码以多种方式执行。 当它由表单按钮执行时它工作(按钮启动一个线程,在循环中它调用这个方法=它的工作原理)。 但是当我从表单中的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 = ...的行上我得到以下exception:

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

为什么?

你需要在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”块中。

你需要写这个:

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

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