Is using Action.Invoke considered best practice?

后端 未结 4 2024
故里飘歌
故里飘歌 2020-12-15 03:27

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

public class ClassA
{
  public event Action OnAdd;

           


        
4条回答
  •  长情又很酷
    2020-12-15 04:03

    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 local = OnAdd;
      if (local != null)
      {
        local("It Happened");
      }
    }
    

提交回复
热议问题