Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
939 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...