I find that the .NET event model is such that I’ll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.
Based on the community suggestions, I’ve used this:
// earlier in the code mCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent); // then private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here }
A couple of observations:
Also you don’t need to create and populate the object array because the args parameter is a ‘params’ type so you can just pass in the list.
I would probably favor
InvokeoverBeginInvokeas the latter will result in the code being called asynchronously which may or may not be what you’re after but would make handling subsequent exceptions difficult to propagate without a call toEndInvoke. What would happen is that your app will end up getting aTargetInvocationExceptioninstead.