• winform线程更新控件


    // 第一步:定义委托类型
    // 将text更新的界面控件的委托类型
    delegate void SetTextCallback(string text);
    
    //第二步:定义线程的主体方法
    /// <summary>
    /// 线程的主体方法
    /// </summary>
    private void ThreadProcSafe()
    {
      //...执行线程任务
    
      //在线程中更新UI(通过控件的.Invoke方法)
      this.SetText("This text was set safely.");
    
      //...执行线程其他任务
    }
    
    //第三步:定义更新UI控件的方法
    /// <summary>
    /// 更新文本框内容的方法
    /// </summary>
    /// <param name="text"></param>
    private void SetText(string text)
    {
      // InvokeRequired required compares the thread ID of the 
      // calling thread to the thread ID of the creating thread. 
      // If these threads are different, it returns true. 
      if (this.lblMsgTips.InvokeRequired)//如果调用控件的线程和创建创建控件的线程不是同一个则为True
      {
        while (!this.lblMsgTips.IsHandleCreated)
        {
        //解决窗体关闭时出现“访问已释放句柄“的异常
        if (this.lblMsgTips.Disposing || this.lblMsgTips.IsDisposed)
        return;
        }
        SetTextCallback d = new SetTextCallback(SetText);
        this.lblMsgTips.Invoke(d, new object[] { text });
      }
      else
      {
        this.lblMsgTips.Text = text;
      }
    }
  • 相关阅读:
    virtualenv -- python虚拟沙盒
    python 多继承详解
    GCDAsyncSocket类库,IOS下TCP通讯使用心得
    TCP长连接与短连接的区别
    SOCKET类型定义及应用
    Ubuntu增加Swap分区大小
    log4j使用说明
    maven资料
    资料推荐
    Idea操作与问题解决
  • 原文地址:https://www.cnblogs.com/zhangmo/p/13552000.html
Copyright © 2020-2023  润新知