Using C# MethodInvoker.Invoke() for a GUI app… is

2019-01-08 09:19发布

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?

5条回答
何必那么认真
2楼-- · 2019-01-08 10:10

Keep in mind that Control.InvokeRequired returns false if you are on background thread AND Control.IsHandleCreated is false. I would safeguard the code with a Debug.Assert that checks for unmanaged handle creation.

查看更多
干净又极端
3楼-- · 2019-01-08 10:13

For WinForms, calling Control.Invoke(Delegate) sends a message to the UI's thead's message pump. The thread then processes the message and calls the delegate. Once it has been processed, Invoke stops blocking and the calling thread resumes running your code.

查看更多
地球回转人心会变
4楼-- · 2019-01-08 10:15

It makes the call on the same thread. You can check by stepping through the code. There is nothing wrong with that approach.

查看更多
Viruses.
5楼-- · 2019-01-08 10:17

Personally I like this method:

private void ExecuteSecure(Action a)
{
    if (InvokeRequired)
        BeginInvoke(a);
    else
        a();
}

And then you can write one-liners like this:

ExecuteSecure(() => this.Enabled = true);
查看更多
放我归山
6楼-- · 2019-01-08 10:19

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.

查看更多
登录 后发表回答