C# 异步打印信息到主线程控件窗

异步委托刷新UI控件

 /// 
 /// 打印线程信息 info
 /// 
 private string info;
 private delegate void FlushClient();//线程代理委托操作主线程控件

 /// 
 /// 打印信息到即时显示控件 
 /// 
 public void PrintMsg(string info)
   {
       this.info = info;
       ThreadFunction();//调用委托 
    }

 /// 
 /// 调用委托 
 /// 
private void ThreadFunction()
 {
      if (this.PntInfo.InvokeRequired)//等待异步
      {
          FlushClient fc = new FlushClient(ThreadFunction);
          this.Invoke(fc);//通过代理调用刷新方法
      }
      else
      {
          this.PntInfo.Text += "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + info + "\r\n";
          this.PntInfo.Focus();//获取焦点
          this.PntInfo.Select(this.PntInfo.TextLength, 0);//光标定位到文本最后
          this.PntInfo.ScrollToCaret();//滚动到光标处 
      }
 }


posted @ 2022-08-31 11:33  Topi  阅读(135)  评论(0)    收藏  举报