Raising events so that they are handled on a the same thread as original subscriber
In dotNET with C# 4.0, How can I ensure that event that happens on an arbitrary thread X will call handlers in the same thread (or synchron开发者_如何转开发ization context) as the subscribing thread A, B, or C.
I am trying to avoid having to put in threading-related code into handler method or event site.
It would be really great if I wouldn't have to change += and -= subscription, as well as "public event EventHandler myevent;" code.
I don't think you can directly do this. The best you can do is register handlers which will run on some arbitrary thread, but which will pass the data to the original thread.
This can currently be done with a TaskCompletionSource,
combined with the default behavior of async/await that brings things back to the calling synchronization context.
精彩评论