使用Action.Invoke认为是最佳做法?做法、Action、Invoke

2023-09-03 12:12:14 作者:厮守她、

如果我有低于code,我应该只是调用Action还是应该叫Action.Invoke?

 公共类ClassA的
{
  公共事件动作<字符串> OnAdd;

  私人无效SomethingHappened()
  {
    如果(OnAdd!= NULL)
     OnAdd(事情发生); //它应该是OnAdd.Invoke(事情发生)???????
  }
}

公共类ClassB的
{

  公共ClassB的()
  {
    VAR MyClass的=新ClassA的();
    myClass.OnAdd + =添加;
  }

  私人无效添加(字符串输入)
  {
    //做一点事
  }
}
 

解决方案

这两个是等价的,则编译器会将 OnAdd(事情发生); OnAdd.Invoke(事情发生); 为您服务。

我想它是preference的事,但是我个人preFER了更简洁的形式。

顺便说一句,这是一般preferable调用它,以避免出现竞争状态,其中 OnAdd 不为空之前采取类级别代表的本地副本在它被选中,但是是在它被调用时的时间:

 私人无效SomethingHappened()
{
  动作<字符串>当地= OnAdd;
  如果(地方!= NULL)
  {
    本地(事情发生);
  }
}
 
WF4.0 基础篇 二十五 ActivityAction与InvokeAction

If I have the below code, should I just call the Action or should it call Action.Invoke?

public class ClassA
{
  public event Action<string> OnAdd;

  private void SomethingHappened()
  {
    if (OnAdd != null)
     OnAdd("It Happened"); //Should it be OnAdd.Invoke("It Happened") ???????
  }
}

public class ClassB
{

  public ClassB()
  {
    var myClass = new ClassA();
    myClass.OnAdd += Add;
  }

  private void Add(string Input)
  {
    //do something
  }  
}

解决方案

The two are equivalent, the compiler converts OnAdd("It Happened"); into OnAdd.Invoke("It Happened"); for you.

I guess it's a matter of preference, however I personally prefer the terser form.

As an aside, it is generally preferable to take a local copy of a class level delegate before invoking it to avoid a race condition whereby OnAdd is not null at the time that it is checked, but is at the time that it is invoked:

private void SomethingHappened()
{
  Action<string> local = OnAdd;
  if (local != null)
  {
    local("It Happened");
  }
}