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?
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.
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.
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#.
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.
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