I have 2 objects. Foo and Bar in two different threads. Now I want to raise an event in Foo but in the thread of Bar.
and how can I use SynchronizationContext.Current for that?
Neither “Foo” nor “Bar” really have threads… you would need an external message-pump mechanism to push messages between threads, such as is provided in winforms (Control.Invoke) and WPF (Dispatcher). Alternatively, something like a (synchronized) producer/consumer queue would suffice if you don’t mind one of the threads being devoted to waiting (passively) for messages.
Unless you have written your own sync-context, it is impossible for us to say what
SynchronizationContext.Current will be; in many cases it is
Can you add more context to the problem?
Synchronization context is used more for Silverlight apps, isn’t it? If you need different operations to run in the same thread, launch each operation with SynchronizationContext.Send().
(hopefully that when you say you want to run it in the thread of Bar, that you’re referring the the UI thread that the synchronization context will run any Send()d callbacks in. If thats the case, only the event from Foo needs to be Send()d).
The only way I can think of is to use the InvokeRequired() and BeginInvoke() methods that are built in to UI elements to help you ensure that all code modifying a UI element is executed from the same thread used to create the element.
… Before Foo starts, in Bar, create an instance of some UI Element, say a label… Then When the event is raised in Foo, in the event handler, call BeginInvoke() on that UI element, That will guarantee that the code that runs will be run on Bar…
But WHy do you want to do this ?