分享一个跨线程访问控件的很实用的方法

看CefSharp的时候好像发现一个很好用用来跨线程访问控件的方法。在这个异步编程的时代,应该还是很好用的。

代码:

    /// <summary>
    /// Executes the Action asynchronously on the UI thread, does not block execution on the calling thread.
    /// </summary>
    /// <param name="control">the control for which the update is required</param>
    /// <param name="action">action to be performed on the control</param>
    public static void InvokeOnUiThreadIfRequired(this Control control, Action action)
        {
            if (control.InvokeRequired)
            {
                control.BeginInvoke(action);
            }
            else
            {
                action.Invoke();
            }
        }

上面的这个方法有时候也有点问题。因为它是不阻塞方法的调用方的,当我们希望通过UI操作来决定调用方下一步执行方向的的话,这个方法就不能使用了。可以将是否阻塞调用方作为参数传入。

修改代码:

        public static void InvokeOnUiThreadIfRequired(this Control control, Action action, bool isBlock = false)
        {
            if (control.InvokeRequired)
            {
                if (isBlock)
                    control.Invoke(action);
                else
                    control.BeginInvoke(action);
            }
            else
            {
                action.Invoke();
            }
        }

使用:

                this.InvokeOnUiThreadIfRequired(() =>
                {
                    //控件访问
                    this.Text = "changed";
                });        

或者

         this.InvokeOnUiThreadIfRequired(() =>
                {
                    //控件访问
                    this.Text = "changed";
                },true);//阻塞调用线程,未测试

That‘s all.

原文地址:https://www.cnblogs.com/jianIsTheBest/p/10604641.html