zoukankan      html  css  js  c++  java
  • C#: 线程间操作无效: 从不是创建控件“dataGridView”的线程访问它

    最近在修改自动化小工具,用多线程来解决后台拷贝导致WinForm界面卡死的情况,但是遇到过错:线程间操作无效: 从不是创建控件“dataGridView”的线程访问它。

    这是因为在多线程程序中,新创建的线程不能访问UI线程创建的窗口控件,如果需要访问窗口中的控件,有2种解决方法:

    1. 在Form_Load中添加:

    //取消跨线程检查
    Control.CheckForIllegalCrossThreadCalls = false;

    这样进行非安全线程访问时,运行环境就不去检验它是否是线程安全的。

    但是不推荐这种方法!!!

    2. 利用委托机制实现线程安全。

    就是将你所要操作的代码放到一个代理中,然后将这个代理交给创建这个控件的线程来执行你的代码。

    //声明委托:
    private delegate void DelegateDataGridViewWRLUI();
    //使用委托在多线程中执行:
    DelegateDataGridViewWRLUI delegateDataGridViewWRLUI = delegate
    {
        this.dataGridViewWRL.DataSource = dataList;
        this.dataGridViewWRL.Refresh();
        this.dataGridViewWRL.EditMode = DataGridViewEditMode.EditOnEnter;//鼠标单击编辑
        this.dataGridViewWRL.RefreshEdit();
        this.dataGridViewWRL.Columns[1].Frozen = true; //固定左侧2列
    };
    this.dataGridViewWRL.Invoke(delegateDataGridViewWRLUI);
  • 相关阅读:
    android自定义View之NotePad出鞘记
    一个电商项目的Web服务化改造
    一个电商项目的Web服务化改造
    POJ 2886 Who Gets the Most Candies?
    POJ 2392 Space Elevator
    POJ 1276 Cash Machine
    POJ 2063 Investment
    CodeForces 159c String Manipulation 1.0
    Gym
    FZU 1921 栀子花开
  • 原文地址:https://www.cnblogs.com/danvy/p/10414744.html
Copyright © 2011-2022 走看看