Events and Multithreaded code in .NET

元气小坏坏 提交于 2019-12-31 05:43:09

问题


Project is C#.

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.

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?

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.


回答1:


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.

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

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.

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).




回答2:


Using a timer, or responding to an event, the UI thread (or a databound object on the thread) could poll a "status" object and limit the amount of work the UI must do.




回答3:


Have you looked at the Facade, Proxy, Factory and Singleton patterns?

If you implement your core object as a Singleton, and provide proxy and factory methods to produce and deliver these to callers of your library this becomes fairly straight-forward. The Facade pattern can make this easier by abstracting away most of the internals of what is going on in the backend.

Combining Factory and Singleton, and ensuring that all classes you want exposed have constructors requiring your main object is a good way to enforce this design. I dont know the main requirements/design of your library, so I am not sure if this would work for you or not.



来源:https://stackoverflow.com/questions/1943593/events-and-multithreaded-code-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!