.NET中的事件和多线程代码 [英] Events and Multithreaded code in .NET

查看:153
本文介绍了.NET中的事件和多线程代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

项目是C#。

所以我有一堆旨在作为库运行的多线程代码。这是在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.

这样,您的图书馆将不可知(可以在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).

这篇关于.NET中的事件和多线程代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆