C# 异常:System.InvalidOperationException:“线程间操作无效: 从不是创建控件“Button”的线程访问它。”

当使用多线程功能时,在子线程里修改UI控件参数时,如下

private void uiButton1_Click(object sender, EventArgs e)
        {

            try
            {
                //启动外部程序
                Process proc = Process.Start(appName);
                this.uiButton1.Enabled = false;
                if (proc != null)
                {
                    //监视进程退出
                    proc.EnableRaisingEvents = true;
                    //指定退出事件方法
                    proc.Exited += new System.EventHandler(proc_Exited);
                }
                
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        ///启动外部程序退出事件
        /// </summary>
        void proc_Exited(object sender, EventArgs e)
        {
            this.uiButton1.Enabled = true;
        }

出现这个异常

后来经过多方查询得出以下解决方案:

也可以使用委托方式

this.Invoke(new EventHandler(delegate
{
	this.uiButton1.Enabled = true;
}));

因为该子线程不是UI的创建者,所以子线程应该使用一个委托让UI线程来执行this.uiButton1.Enabled = true;操作。
其中EventHandler是一个事件委托,其定义如下:

using System.Runtime.InteropServices;

namespace UI
{
    [Serializable]
    [ComVisible(true)]
    public delegate void EventHandler(object sender, EventArgs e);
}

如果对委托类型不了解,也可以直接按照Lamda表达式的写法,改写成如下形式。

this.Invoke(new Action(() =>
{
	this.uiButton1.Enabled = true;
}));

猜你喜欢

转载自blog.csdn.net/weixin_44684272/article/details/110940443