Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# MethodInvoker.Invoke() for a GUI app... is this good?

Using C# 2.0 and the MethodInvoker delegate, I have a GUI application receiving some event from either the GUI thread or from a worker thread.

I use the following pattern for handling the event in the form:

private void SomeEventHandler(object sender, EventArgs e) {     MethodInvoker method = delegate         {             uiSomeTextBox.Text = "some text";         };      if (InvokeRequired)         BeginInvoke(method);     else         method.Invoke(); } 

By using this pattern I do not duplicate the actual UI code but what I'm not sure about is if this method is good.

In particular, the line

method.Invoke() 

does it use another thread for invoking or does it translate somewhat to a direct call to the method on the GUI thread?

like image 207
Stécy Avatar asked Apr 23 '09 15:04

Stécy


People also ask

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

How do I start learning C?

Get started with C. Official C documentation - Might be hard to follow and understand for beginners. Visit official C Programming documentation. Write a lot of C programming code - The only way you can learn programming is by writing a lot of code.

Is C hard to learn?

While C is one of the more difficult languages to learn, it's still an excellent first language pick up because almost all programming languages are implemented in it. This means that once you learn C, it'll be simple to learn more languages like C++ and C#.


1 Answers

The method.Invoke() call executes the delegate on the current executing thread. Using the BeginInvoke(method) ensures that the delegate is called on the GUI thread.

This is the correct way of avoiding code duplication when the same method can be called both from the GUI thread and other threads.

like image 173
CMerat Avatar answered Sep 22 '22 16:09

CMerat