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 }
Answers. 1) No. The event handlers are run off the timer tick event as well as the swapping of thread execution.
Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on. public: property bool InvokeRequired { bool get(); }; C# Copy.
In the first line we get to know whether the control we want to access is created on the same thread or another thread. If it's created on another thread then it will execute the second line.
Invoke(DispatcherPriority, TimeSpan, Delegate, Object) Executes the specified delegate at the specified priority with the specified argument synchronously on the thread the Dispatcher is associated with. Invoke(DispatcherPriority, Delegate, Object, Object[])
I have some code for this online. It's much nicer than the other suggestions; definitely check it out.
Sample usage:
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { // You could use "() =>" in place of "delegate"; it's a style choice. this.Invoke(delegate { // Do the dirty work of my method here. }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With