zoukankan      html  css  js  c++  java
  • WinForm中跨线程操作控件

    在WinForm编程时会遇到通过后台线程操作界面的情况,直接在后台线程执行的方法中直接操作控件会报错,这时候就要使用跨线程方式间接操作控件。下面是两种实现方式。
     
    1、采用定义delegate的方式
    private delegate void SetTextBoxValueDelegate(string value);
    private void SetTextBoxValue(string value)
    {
        if (this.txtInfo.InvokeRequired)//判断是否跨线程请求
        {
            SetTextBoxValueDelegate myDelegate = delegate(string text) { txtInfo.Text = text; };
            txtInfo.Invoke(myDelegate, value);
        }
        else
        {
            txtInfo.Text = value;
        }
    }

     

    2、采用Action<T>的方式(推荐)
    private void SetTextBoxValue(string value)
    {
        Action<string> setValueAction = text => txtInfo.Text = text;//Action<T>本身就是delegate类型,省掉了delegate的定义
        if (this.txtInfo.InvokeRequired)
        {
            txtInfo.Invoke(setValueAction, value);
        }
        else
        {
            setValueAction(value);
        }
    }
  • 相关阅读:
    1203 forms组件
    1128 聚合查询 orm字段及属性
    1127 模型层orm表操作
    1126 视图层与模板层
    1122 django中orm操作
    1121 Django操作
    1125 视图层
    搭建并行开发环境MPICH2
    Linpack之HPL测试 (HPL Benchmark)
    安装NetCDF及HDF5
  • 原文地址:https://www.cnblogs.com/conexpress/p/WinForm_Thread_Operate_Control.html
Copyright © 2011-2022 走看看