Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest Way to Invoke Cross-Thread Events

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 } 
like image 883
Nick Avatar asked Aug 22 '08 13:08

Nick


People also ask

Do events run on separate threads?

Answers. 1) No. The event handlers are run off the timer tick event as well as the swapping of thread execution.

What is InvokeRequired in C#?

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.

What is cross threading in C#?

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.

What is thread invoke?

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[])


1 Answers

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.     }); } 
like image 83
Domenic Avatar answered Sep 24 '22 04:09

Domenic