是否可以移动控件或至少将控件复制到另一个线程,然后再创建它。原因是我希望控件完全加载到后台线程中然后一旦完成加载我想将控件移动到另一个线程。例如:
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?
}
答案 0 :(得分: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();
}
答案 1 :(得分:0)
不,这是不允许的。所有控件必须由单线程提供服务。它是用于创建窗口的线程,通常是进程的第一个线程。
答案 2 :(得分:0)
您可以使用Invoke从单独的线程更新控件。看看这里
Invoke((MethodInvoker)delegate
{
//use control
});