在类库中获取 UI 调度程序
我想设计一个类库并计划使用多线程(即BackgroundWorker
)。如果我计划将字段绑定到库消费前端的 GUI,我将必须注意线程上下文,从中对字段进行更新。正如我所读到的,将 GUI 调度程序的引用传递给库并不是一个好主意。但是我如何才能访问将使用该库的应用程序的调度程序呢?这可能吗?
我尝试了 Application.Current.Dispatcher
并添加了对 WindowBase
的引用(因为我无法添加 System.Windows
),但仍然无法解析调度程序对象。
I'd like to design a class library and plan to use mutli-threading (i.e. BackgroundWorker
). I will have to watch out for the thread context, from which updates are made for fields, if I plan to bind them to the GUI of the library consuming frontend. It's not a good idea to pass the reference of the GUI dispatcher to the library, as I read. But how can I get access to the dispatcher of the application that will use the library? Is this possible?
I tried Application.Current.Dispatcher
and added a reference to WindowBase
(as I didn't have the possibility to add System.Windows
), but still can't resolve the dispatcher object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Application 类在
PresentationFramework.dll
中定义。您需要引用它才能通过Application.Current.Dispatcher
访问调度程序。The Application class is defined in
PresentationFramework.dll
. You need to reference that in order to be able to access the dispatcher throughApplication.Current.Dispatcher
.我遇到了同样的问题,即无法解析 Application.Current.Dispatcher 并最终将客户端 gui 调度程序传递到仅包含调度程序引用的库(参考 WindowsBase + 使用 System.Windows.Threading)。
我更喜欢这个选项,让我的非 GUI 库必须携带对PresentationFramework.dll 的引用(这似乎不自然)。
我猜一个是 6 个,另一个是 6 个……
I had same issue ie not being able to resolve Application.Current.Dispatcher and ended up passing the client gui dispatcher down to the library which just holds a Dispatcher ref (reference WindowsBase + using System.Windows.Threading).
I prefer this option that having my non GUI lib have to carry a ref to PresentationFramework.dll (which doesn't seem natural).
I guess its 6 of one, half a dozen of the other...
如果您确保(例如使用类的静态成员)可以方便地引用 UI 调度程序,您可以执行以下操作:
我研究过的一两个 MVVM 框架可以执行以下操作 :这。
如果您不想将此
Dispatcher
引用传递给库,可以选择 IoC 容器。您还可以将其放入 exe 和类库都需要引用的类和接口的 Common.dll 中。 exe可以设置正确的引用,并且类库可以调用Run()
方法。If you make sure (such as with static members of a class) that you have a handy reference to the UI
Dispatcher
, you can do this:One or two MVVM frameworks I've looked at do stuff like this.
If you don't want to pass this
Dispatcher
reference down to the library, IoC containers are an option. You could also put this in a Common.dll for classes and interfaces that both the exe and class libraries need to reference. The exe can set up the correct reference, and the class library can call theRun()
method.