事件和多线程美元的.NET C $Ç多线程、美元、事件、NET

2023-09-07 00:37:37 作者:枕下悲绪

项目是C#。

所以,我有一大堆的多线程code,它被设计为运行作为一个库。这是从UI一个单独的项目。

So I have a bunch of multithreaded code that is designed to be run as a library. It's in a seperate project from the UI.

我的图书馆有一个需要创建任何会断火在创建活动之前,中央对象。

My library has a central object that needs to be created before anything that would fire off events is created.

是否有可能在一些对象传递这个主对象,以使我的事件,可以计算出,当需要他们被调用,以返回到主UI线程?

Is it possible for this master object to be passed in some objects so that my events can figure out when they would need to be invoked to get back to the main UI thread?

我真的很想保持UI从有做一堆调用,因为他的事件处理程序几乎总是会被一些随机的后台线程调用。

I'd really like to keep the UI from have to do a bunch of invoking since his event handlers are almost always going to be called from some random background thread.

推荐答案

从你描述一下,你最好的选择可能是使所有的物体拍摄的的SynchronizationContext 作为其构造函数的参数。

From what you're describing, your best option might be to make all of your objects take a SynchronizationContext as a argument in their constructor.

如果你这样做,当你需要提高一个事件,你可以使用的 SyncrhonizationContext.Post 以援引UI线程上的事件。

If you do that, when you need to raise an event, you can use SyncrhonizationContext.Post to "invoke" the event on the UI thread.

这样,你的图书馆将UI无关(可以工作在Windows窗体或WPF),并且可以根据需要在UI线程上引发事件。

This way, your library will be UI-agnostic (could work in Windows Forms or WPF), and you can raise events on the UI thread as needed.

使用的 SynchronizationContext.Current (它给你的Windows窗体和WPF应用程序的有效范围内,在不参考拉动要么)。

The user of your library would just create your object using SynchronizationContext.Current (which gives you a valid context in Windows Forms and WPF applications, without pulling in a reference to either).