C#在跨线程操作控件时, 一般如下操作:

在非主线程中调用:

     UpdateInfo(info);

 

delegate void updateInfoDelegate(string info);

private void UpdateInfo(string info)

{

      if (this.InvokeRequired)

     {

          updateInfoDelegate d= new updateInfoDelegate(UpdateInfo);

          this.Invoke(d, new object[]{info});

      }

      else

      {

            this.label1.Text = info;

       }

}

 

但现在有了 Action<T> 泛型委托, 则就不需要自己申明一个委托了, 只需要将上述蓝色文字部分修改为如下即可:

     this.Invoke(new Action<String>(), info); 

若有多个参数也可以的, 还有 Action<T1, T2>, Action<T1, T2, T3>,Action<T1, T2, T3, T4> ;

若有更多的参数则就将参数封装到一个对象里吧;

若需要返回值, 则用 泛型 Func<T, TResult> 委托即可.

相关文章:

  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
  • 2021-11-18
  • 2021-07-21
  • 2021-05-04
猜你喜欢
  • 2021-12-25
  • 2022-02-02
  • 2021-11-12
  • 2022-03-06
  • 2021-07-28
  • 2021-05-30
  • 2021-05-29
相关资源
相似解决方案