Is using Action.Invoke considered best practice?

后端 未结 4 2018
故里飘歌
故里飘歌 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条回答
  •  Happy的楠姐
    2020-12-15 03:53

    They're exactly equivalent unless you run into a very strange bug around anonymous functions.

    Personally I typically use the shortcut form, but just occasionally it ends up being more readable to explicitly call Invoke. For example, you might have:

    if (callAsync)
    {
        var result = foo.BeginInvoke(...);
        // ...
    }
    else
    {
        foo.Invoke(...);
        // ...
    }
    

    Here the explicit use of Invoke is useful for symmetry.

    See section 15.4 of the C# 4 spec for more details of delegate invocation, although it doesn't explicitly specify it in terms of calling the Invoke method.

提交回复
热议问题