通常,我们以这种方式在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);
}
}发布于 2013-12-19 13:25:43
您可以使用当前的WindowsFormsSynchronizationContext (自.NET 2.0以来就可以使用)
System.Threading.SynchronizationContext.Current.Post(delegate, state);您应该从UI线程获取对上下文的引用,并使其他线程能够访问它,然后其他线程可以使用它在UI线程上执行代码。
这相当于BeginInvoke。对于Invoke等效项,请改用Send方法。
发布于 2013-12-19 13:27:16
使用SynchronizationContext及其Post方法
var sCon=SynchronizationContext.Current;
sCon.Post(new SendOrPostCallback((o) => {
//do your stuffs
}), null);SynchronizationContext只是一种抽象,它代表了您想要在其中进行一些工作的特定环境。作为这种环境的一个例子,Windows窗体应用程序有一个UI线程(虽然有可能存在多个线程,但就本讨论而言并不重要),这是任何需要使用UI控件的工作都需要进行的地方。对于在ThreadPool线程上运行代码并需要将工作编组回UI以便这项工作可以处理UI控件的情况,Windows提供了Control.BeginInvoke方法。将委托交给control的BeginInvoke方法,该委托将在与该控件关联的线程上被调用。
https://stackoverflow.com/questions/20682904
复制相似问题