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

在非托管代码调用托管代码中的控件方法,常常会出现这个错误。
在控件所在的界面使用委托,在初始化的时候 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/p/1223609.html