异常:“在某个线程上创建的控件不能成为在另一个线程上创建的控件的父级。”

vm58 2003-08-25 03:48:16
如何解决?
...全文
723 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
alaisalaix 2003-08-26
  • 打赏
  • 举报
回复
(转载)
The following example demonstrates how to create a background thread that uses a MethodInvoker to update a ProgressBar control at regular intervals:

namespace Microsoft.Samples.WinForms.Cs.ThreadMarshal {
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;


public class ThreadMarshal : System.Windows.Forms.Form {
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.ProgressBar progressBar1;

private Thread timerThread;

public ThreadMarshal() {

// Required by the Windows Forms Designer
InitializeComponent();

}

//This function is executed on a background thread - it marshalls calls to
//update the UI back to the foreground thread
public void ThreadProc() {

try {
MethodInvoker mi = new MethodInvoker(this.UpdateProgress);
while (true) {
//Call BeginInvoke on the Form
this.BeginInvoke(mi);
Thread.Sleep(500) ;
}
}
//Thrown when the thread is interupted by the main thread - exiting the loop
catch (ThreadInterruptedException) {
//Simply exit....
}
catch (Exception) {
}
}

//This function is called from the background thread
private void UpdateProgress() {

//Reset to start if required
if (progressBar1.Value == progressBar1.Maximum) {
progressBar1.Value = progressBar1.Minimum ;
}

progressBar1.PerformStep() ;
}

//Start the background thread to update the progress bar
private void button1_Click(object sender, System.EventArgs e) {
StopThread();
timerThread = new Thread(new ThreadStart(ThreadProc));
timerThread.IsBackground = true;
timerThread.Start();
}

//Stop the background thread to update the progress bar
private void button2_Click(object sender, System.EventArgs e) {
StopThread();
}

//Stop the background thread
private void StopThread()
{
if (timerThread != null)
{
timerThread.Interrupt();
timerThread = null;
}
}

protected override void Dispose(bool disposing)
{
StopThread();
if (disposing) {
if (components != null) {
components.Dispose();
}
}

base.Dispose(disposing);
}

private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.button1.Font = new System.Drawing.Font("Tahoma", 8, System.Drawing.FontStyle.Bold);
this.button1.Location = new System.Drawing.Point(128, 64);
this.button1.Size = new System.Drawing.Size(120, 40);
this.button1.TabIndex = 1;
this.button1.Text = "Start!";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button2.Font = new System.Drawing.Font("Tahoma", 8, System.Drawing.FontStyle.Bold);
this.button2.Location = new System.Drawing.Point(256, 64);
this.button2.Size = new System.Drawing.Size(120, 40);
this.button2.TabIndex = 1;
this.button2.Text = "Stop!";
this.button2.Click += new System.EventHandler(this.button2_Click);
this.progressBar1.Font = new System.Drawing.Font("Tahoma", 8, System.Drawing.FontStyle.Bold);
this.progressBar1.Location = new System.Drawing.Point(10, 10);
this.progressBar1.Size = new System.Drawing.Size(350, 40);
this.progressBar1.TabIndex = 2;
this.progressBar1.Text = "Start!";
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(392, 117);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.button1,
this.button2,
this.progressBar1});
this.Text = "Built using the Designer";

}

[STAThread]
public static void Main(string[] args) {
Application.Run(new ThreadMarshal());
}


}
}


Windows Forms controls can only execute on the thread on which they were created, that is, they are not thread-safe. If you want to get or set properties, or call methods, on a control from a background thread, the call must be marshaled to the thread that created the control.

There are five functions on a control that are safe to call from any thread: InvokeRequired, Invoke, BeginInvoke, EndInvoke and CreateGraphics. For all other method calls, you should use one of the invoke methods.

By default, Windows marshals the calls for you. However, if you are making multiple calls to a control, it is much more efficient to create a method that executes those calls and make the one cross-thread call yourself. You make the cross-thread call by calling one of the Control.Invoke methods. The Invoke methods take a reference to a delegate. Typically, this delegate is an instance of the MethodInvoker delegate.
saucer 2003-08-26
  • 打赏
  • 举报
回复
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q318607

"..................
By design, Windows Form or Control methods cannot be called on a thread other than the one that created the form or control. If you attempt to do this, an exception is thrown. Depending on the exception handling implemented in your code, this exception may cause your application to terminate. If no exception handling is implemented, the following error message is displayed:

An unhandled exception of type 'System.ArgumentException' occurred in system.windows.forms.dll

Additional information: Controls created on one thread cannot be parented to a control on a different thread.

The exception is raised because Windows Forms are based on a single-threaded apartment (STA) model. Windows Forms can be created on any thread; after they are created, however, they cannot be switched to a different thread. In addition, the Windows Form methods cannot be accessed on another thread; this means that all method calls must be executed on the thread that created the form or control.

Method calls that originate outside the creation thread must be marshalled (executed) on the creation thread. To do this asynchronously, the form has a BeginInvoke method that forces the method to be executed on the thread that created the form or control. The synchronous method call is done with a call to the Invoke method.
..................."
xfqiu 2003-08-25
  • 打赏
  • 举报
回复
这问题我原来碰到过.是在多线程应用的时候,应特别注意变量的适用范围,在一个线程(非主线程)内new的一个变量,在另一个线程内是无法使用的.

110,526

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧