Events and multithreaded code in .NET.

Project - C #.

So, I have a bunch of multithreaded code that is designed to work as a library. This is in a separate project from the user interface.

My library has a central object that needs to be created before everything is created that could trigger events.

Is it possible for this main object to be conveyed in some objects so that my events can figure out when they will need to be called in order to return to the main stream of the user interface?

I would really like the user interface to make a bunch of calls, as its event handlers will almost always be called from some random background thread.

0
c # events invoke invokerequired
source share
3 answers

From what you are describing, the best option might be to include all of your objects in the SynchronizationContext as an argument in their constructor.

If you do this when you need to raise an event, you can use SyncrhonizationContext.Post to β€œcall” the event in the thread UI.

Thus, your library will be a UI-agnostic (it can work in Windows Forms or WPF), and if necessary, you can create events in the user interface thread.

Your library user will simply create your object using SynchronizationContext.Current (which gives you a valid context in Windows Forms and WPF applications, without reference to both).

+9
source share

Using a timer or a reaction to an event, a user interface thread (or a data binding object in a thread) can poll a state object and limit the amount of work that the user interface must perform.

0
source share

Have you looked at Facade , Proxy , Factory and Singleton templates?

If you implement your main object as Singleton and provide a proxy server and factory methods for creating and delivering these callers to your library, this becomes pretty straightforward. The FaΓ§ade template can make this easier by diverting most of the internal elements of what happens in the backend.

Combining factory and Singleton and ensuring that all classes you want to open have constructors that require your main object is a good way to ensure that this project runs. I don't know the basic requirements / design of your library, so I'm not sure if this will work for you or not.

0
source share

All Articles