Which C# pattern has better performance to avoid duplicated event handlers?

前端 未结 4 796
你的背包
你的背包 2021-02-14 03:54

There are basically two patterns in avoiding duplicated registering of event handlers: (According to this discussion: C# pattern to prevent an event handler hooked twice)

<
4条回答
  •  -上瘾入骨i
    2021-02-14 04:19

    I don't think this matters a lot, both in assumed performance gain and actual difference.

    Both GetInvocationList and -= walk the internal array _invocationList. (See source)

    The LINQ extension method Contains will take more time since it needs the entire array to be walked and converted, returned and then checked by Contains itself. The Contains has the advantage it doesn't need to add the event handler if it exists which will mean some performance gain.

提交回复
热议问题