Action<T> 泛型委托 在跨线程访问控件委托中的应用

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> 委托即可.

原文地址:https://www.cnblogs.com/csMapx/p/2171650.html