How is it right to challenge the event from the flow?
-
There's a facility A (the event manager) that has a flow that occasionally triggers this event. There's an object B that's signed for the event and receives data from A. When B processs the event, there's an exception as if class B is working in the flow of A, is that normal? I fixed it through SynchronizationContext, but can there be better options?
-
Events at NET are delivered in the same flow as those produced. If you need to deal with another flow, there are several ways:
Get the challenge in the right context. https://msdn.microsoft.com/en-us/library/hh199422%28v=vs.110%29.aspx ♪ https://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke%28v=vs.120%29.aspx ♪ https://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.post%28v=vs.110%29.aspx , depending on the type of your application.
Example:
void OnEvent(object sender, EventArgs args) { Control.BeginInvoke((Action)(() => OnEventReally(sender, args))); }
async void OnEvent(object sender, EventArgs args) { await Dispatcher.InvokeAsync(() => OnEventReally(sender, args)); }
Go to Reactive Extensions and use it. https://msdn.microsoft.com/en-us/library/hh229634%28v=vs.103%29.aspx :
Observable.FromEventPattern<EventArgs>(sender, "EventName") .ObserveOn(SynchronizationContext.Current) .Subscribe(ev => { ... });
Move to async processors and deliver the implementation in the right context with help
RedirectTo
as described in https://ru.stackoverflow.com/a/458425/10105 (samare, yes).async void OnEvent(object sender, EventArgs args) { await AsyncHelper.RedirectTo(Dispatcher); ... }