2011-01-27 39 views
0

是否可以移动控件或至少将控件复制到另一个线程,然后创建它。原因是我想控制加载完全在后台线程,然后一旦完成加载我想将控制移动到另一个线程。例如:winforms - 将控件移动到另一个线程

BackgrundworkRunasync(object sender, DoWorkEventArgs e) 
{ 
    var GetData = GetData(); 
    CreateControl mycontrol = new CreateControl() //Tyep of WindowsForm 
    mycontrol.Data = GetData; 
    e.Result = mycontrol; 
} 

BackGroundWorkerComplete (object sender, RunWorkerCompletedEventArgs e) 
{ 
    CreateControl con = (CreateControl)e.Result; 
    con.mdiparent = this; 
    con.Show(); 

//Of course this is a cross threading exception. Can I move this control to the current thread or even create a control in the current thread and do a deep copy? Optimally I just want to move the control to another thread, can you do this? 
} 

回答

1

不,这是不可能的。在主线程上创建控件必须

您应该修改代码那样:

BackgrundworkRunasync(object sender, DoWorkEventArgs e) 
{ 
    e.Result = GetData(); 
} 

BackGroundWorkerComplete (object sender, RunWorkerCompletedEventArgs e) 
{ 
    CreateControl mycontrol = new CreateControl() //Tyep of WindowsForm 
    mycontrol.Data = e.Result; 
    myControl.mdiparent = this; 
    myControl.Show(); 
} 
0

不,这是不允许的。所有的控件都必须由单线程提供服务。它是您用来创建窗口的线程,通常是该进程的第一个线程。

相关问题