K
K
Ko12015-12-13 23:19:03
.NET
Ko1, 2015-12-13 23:19:03

How to correctly call an event from a thread?

There is an object A (event sender) in which a thread is running, from which this event is periodically called. There is an object B that subscribes to the event and receives data from object A. When B handles the event, an exception is thrown as if the method of class B is running on the thread of object A, is this normal? Fixed via SynchronizationContext, but maybe there are better options?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2015-12-14
@Ko1

When B handles the event, an exception is thrown as if B's ​​class method is running on object A's thread, is that normal?

Well, you invoked the event in another thread, why would it automatically look for another, "necessary" thread? You yourself must know in which thread you raise the event. If it is internal, then it can also generate it correctly in the worker thread, and if the event is visible from the outside (i.e., you can subscribe from outside the class), and class A itself abstracts the existence and operation of some other thread (i.e., clients should NOT know this) - then it is logical to take care of the transfer of the event to the desired stream. Remember that it is you who determines the threading architecture of the application, and it is up to you to decide which code will be processed within which threads.
It's fine if you're using a subsystem that has a SynchronizationContext implementation, such as WinForms or WPF. If this is not your option, then you need to provide your own implementation, or refuse to use it and explicitly use message queues to communicate between threads.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question