我在Windows窗体中有一些代码有点像这样:
button1_Click(object sender, EventArgs e)
{
Widget myWidget = new Widget(...bunch of constructor parameters...);
myWidget.Property1 = "blah"; // other properties get set here too...
myWidget.InterestingThingHappened += InterestingThingHappened;
Parallel.Invoke(myWidget.RunInterestingLongRunningProcess());
}
private void InterestingThingHappened(object sender, EventArgs e)
{
myLabel.Invoke(new Action(() => myLabel.Text = "An interesting thing happened!"))
}
当我运行它时,应用程序只是冻结,直到我在任务管理器中杀死它。然后我看到一个异常说,在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke。' button1_Click
显然是一个控件事件处理程序,因此在此代码运行之前完全创建表单。我完全不知道这意味着什么。有人可以帮忙吗?
答案 0 :(得分:0)
使用BeginInvoke()
而不是Invoke()
完全修复了问题。 UI实时更新。为什么?谁知道?