The main problem is, that raising an event from one thread can invoke delegates which should only invoked in a certain thread context. After doing some research on this problem i thought, maybe its possible to pass some kind of synchronization context along with each subscription to an event:
SomeClass.SmartSyncEvent += (myDelegate, someReferenceToAThread);
and then raise the event and it somehow does:
foreach(subscriber)
{
someReferenceToAThread.Invoke(myDelegate);
}
This is super pseudo code, but maybe someone has already done things like this, or knows of any .NET classes which can set up such a pattern.
thanks!
The best way to do this is pass
SomeClassa synchronization context viaISynchronizeInvoke.This pattern is similar to the way
System.Timers.Timeris implemented. The problem with it is that every subscriber will be marshaled onto the same synchronizing object. It does not appear that this is what you want though.Fortunately delegates store the class instance upon which the method should be invoke via the
Targetproperty. We can exploit this by extracting it before we invoke the delegate and using it as the synchronizing object assuming of course that it is aISynchronizeInvokeitself. We could actually enforce that by using custom add and remove event accessors.This is a lot better in that each subscriber can be marshaled independently of the others. The problem with it is that the handlers must be instance methods that reside in an
ISynchronizeInvokeclass. Also,Delegate.Targetis null for static methods. This is why I enforce that constraint with the customaddaccessor.You could make it execute the handlers synchronously if
Delegate.Targetwere null or otherwise could not be casted into a useful synchronizing object. There are a lot of variations on this theme.In WPF you could code for
DispatcherObjectinstead ofISynchronizeInvoke.