【发布时间】:2013-12-19 13:23:04
【问题描述】:
通常我们以这种方式在 UI 线程上调用:
myControl.Invoke((MethodInvoker)delegate() { Foo(); });
他们有没有任何方法可以在没有任何控制实例的情况下做到这一点?我的意思是这样的:
System.Windows.Forms.Thread.Invoke(...);
解决方案
dcastro 给出的解决方案,使用WindowsFormsSynchronizationContext。这是一个非常简单的表单示例:
public partial class FrmFoo : Form
{
SynchronizationContext uiThread;
public void FrmFoo()
{
// Needs to assign it from somewhere in the UI thread (in constructor for example)
uiThread = WindowsFormsSynchronizationContext.Current;
}
void AsyncBar()
{
uiThread.Send(delegate(object state)
{
// UI Cross-Thread dangerous manips allowed here
}, null);
}
}
【问题讨论】:
-
这确实是旧的做事方式。告诉人们您正在使用的 .NET 版本将有助于带来更现代的答案......以及一个用例。
-
@SimonWhitehead .NET 2 兼容性是技术限制,我别无选择
标签: c# multithreading winforms delegates invoke