C# Firing events within the thread they are added

c#, events, multithreading

Solution

You want to do inter thread communication. Yes it is possible. Use System.Windows.Threading.Dispatcher http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx

The Dispatcher maintains a prioritized queue of work items for a specific thread. When a Dispatcher is created on a thread, it becomes the only Dispatcher that can be associated with the thread, even if the Dispatcher is shut down. If you attempt to get the CurrentDispatcher for the current thread and a Dispatcher is not associated with the thread, a Dispatcher will be created. A Dispatcher is also created when you create a DispatcherObject. If you create a Dispatcher on a background thread, be sure to shut down the dispatcher before exiting the thread.

Problem

Consider two classes; `Producer` and `Consumer` (the same as classical pattern, each with their own threads). Is it possible for `Producer` to have an `Event` which `Consumer` can register to and when the producer triggers the event, the consumer's event handler is run in its own thread? Here are my assumptions: `Consumer` does not know if the `Producer`'s event is triggered within his own thread or another. Neither `Producer` nor `Consumer` are descendants of `Control` so they don't have `BeginInvoke` method inherited. PS. I'm not trying to implement `Producer` - `Consumer` pattern. These are two simple classes which I'm trying to refactor the producer so it incorporates threads. [UPDATE] To further expand my problem, I'm trying to wrap a hardware driver to be worked with in the simplest way possible. For instance my wrapper will have a `StateChanged` event which the main application will register to so it will be notified when hardware is disconnected. As the actual driver has no means other than polling to check its presence , I will need to start a thread to check it periodically. Once it is not available anymore I will trigger the event which needs to be executed in the same thread as it was added. I know this is a classical Producer-Consumer pattern but since I'm trying to simplify using my driver-wrapper, I don't want the user code to implement consumer. [UPDATE] Due to some comments suggesting that there's no solution to this problem, I would like to add few lines which might change their minds. Considering the `BeginInvoke` can do what I want, so it shouldn't be impossible (at least in theory). Implementing my own `BeginInvoke` and calling it within the `Producer` is one way to look at it. It's just that I don't know how `BeginInvoke` does it!

Original source