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

浪尽此生 提交于 2019-11-27 06:41:39

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.

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);

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!