现在的位置: 首页 > 综合 > 正文

C# 子线程操作主窗体控件的解决方法

2013年02月15日 ⁄ 综合 ⁄ 共 769字 ⁄ 字号 评论关闭
初试C#,结果发现原在Java里面可以实现的子线程调用主窗体空间,在C#中会抛出异常,子线程和运行窗体的线程在不同的空间,这样的跨线程调用C#编译器视为危险调用方法,所以抛出异常。

      使用委托和Invoke方法。

     private delegate void addStatusUnSafe(string status);
      public void addStatus(string status)
      {
          DateTime dt = System.DateTime.Now;
          string now = "[" + dt.ToShortDateString() + " " + dt.ToShortTimeString() + "]";

          if (this.listBoxStatus.InvokeRequired)
          {
              addStatusUnSafe aus = new addStatusUnSafe(addStatus);
              this.listBoxStatus.Invoke(aus, new string[] { status });
          }
          else
          {
              this.listBoxStatus.Items.Add(now + status);
              if (this.listBoxStatus.Items.Count > 0)
              {
                  this.listBoxStatus.SelectedIndex = this.listBoxStatus.Items.Count - 1;
              }
          }

      }

 

 

抱歉!评论已关闭.