问题描述
我目前正在尝试编写一个组件,该组件的某些部分应在UI线程上运行(解释会很长).因此,最简单的方法是将控件传递给它,并在其上使用InvokeRequired/Invoke.但是我认为将控件引用传递给数据/背景"组件不是一个好的设计,因此我正在寻找一种无需在控件上可用就可以在UI线程上运行代码的方法. .类似于Application.Dispatcher.Invoke in WPF ...
I currently trying to write a component where some parts of it should run on the UI thread (explanation would be to long).So the easiest way would be to pass a control to it, and use InvokeRequired/Invoke on it.But I don't think that it is a good design to pass a control reference to a "data/background"-component, so I'm searching for a way to run code on the UI thread without the need of having a control available.Something like Application.Dispatcher.Invoke in WPF...
任何想法,谢谢马丁
any ideas,thxMartin
推荐答案
有一种更好,更抽象的方法可以在WinForms和WPF上使用:
There's a better, more abstract way to do this that works on both WinForms and WPF:
System.Threading.SynchronizationContext.Current.Post(theMethod, state);
之所以有效,是因为WindowsForms安装了 WindowsFormsSynchronizationContext
对象作为当前同步上下文. WPF做类似的事情,安装它自己的专用同步上下文( DispatcherSynchronizationContext
).
This works because WindowsForms installs a WindowsFormsSynchronizationContext
object as the current sync context. WPF does something similar, installing it's own specialized synchronization context (DispatcherSynchronizationContext
).
.Post
对应control.BeginInvoke
,.Send
对应control.Invoke
.
这篇关于在没有控制对象的情况下在UI线程上运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!