我有以下功能
private void UnsubscribeSubscribe(Action action)
{
action.BeginInvoke(action.EndInvoke, null);
}
每当我传入修改我的控件数据源的操作时,都不会发生任何事情。我知道正在调用该操作,因为我正在运行的查询返回结果。我读到你只能从添加它们的同一个线程修改winform控件。我怎样才能做到这一点?
例如,跑步 UnsubscribeSubscribe(()=> {Foobar.DataSource = GetResults()});
GetResults()
将正常运行,但数据源将保持不变。
答案 0 :(得分:5)
您需要在创建控件底层句柄的线程上调用委托。 Control.BeginInvoke仅用于此。
答案 1 :(得分:3)
您使用的是错误的方法。委托的BeginInvoke()方法始终在线程池线程上运行委托目标。毒害用户界面。您需要使用Control.BeginInvoke()。就像表单的BeginInvoke方法一样。虽然命名相似,但它与委托的BeginInvoke()方法有 nothing 。首先,您不必(也不应该)调用EndInvoke()。
答案 2 :(得分:2)
如果您需要从不同的线程然后GUI线程对UI线程执行操作,那么您应该使用Invoke
这样的方法(此示例用于文本框 - 来自msdn):< / p>
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
还有另一种使用SynchronizationContext课程的方法 - 您可以阅读有关使用它的信息here