线程间操作无效: 从不是创建控件 的线程访问它

本文介绍了一种在非托管代码中调用托管代码控件方法的解决方案,通过使用委托来实现跨线程更新DataGridView控件的具体步骤。该方法有效地避免了因尝试从其他线程直接修改UI控件而引发的异常。
在非托管代码调用托管代码中的控件方法,常常会出现这个错误。
在控件所在的界面使用委托,在初始化的时候 delegateGrid = new DelegateGrid(GridRefresh);

private delegate void DelegateGrid(int channelId, string columnName, string columnValue);
        DelegateGrid delegateGrid = null;
        void GridRefresh(int channelId, string columnName, string columnValue)
        {
            for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
            {
                if (dataGridViewX1.Rows[i].Cells["通道号"].Value.ToString() == channelId.ToString())
                {
                    dataGridViewX1.Rows[i].Cells[columnName].Value = columnValue;
                    return;
                }
            }
        }
        public void OnGridRefresh(int channelId, string columnName, string columnValue)
        {
            if (null != delegateGrid)
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(delegateGrid, channelId, columnName, columnValue);
                }
                else
                {
                    delegateGrid(channelId, columnName, columnValue);
                }
            }
        }
在其他线程中调用 OnGridRefresh 这个公用方法。

转载于:https://www.cnblogs.com/todd/archive/2008/06/17/1223609.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值