Copying delegates

自古美人都是妖i 提交于 2019-12-05 01:14:41

Delegates are immutable, so the reference obtained in that code is guaranteed to not change. If a user subscribes or unsubscribes after the null check, a new delegate will be created and set to the event. However, since you have a reference to a completely different object and invoke that, you don't have to worry about it being null.

You are correct; it is copying the reference.

However, delegates are immutable; when you add a handler to an event, a new delegate is created, combining the current handler(s) with the new one, and is then assigned to the field.

The Delegate instance that the field is referencing cannot change, so it does avoid the race condition.

Eric Lippert already covered this in a very detailed post.

This is from MSDN too..

"The invocation list of a delegate is an ordered set of delegates in which each element of the list invokes exactly one of the methods represented by the delegate. An invocation list can contain duplicate methods. During an invocation, methods are invoked in the order in which they appear in the invocation list. A delegate attempts to invoke every method in its invocation list; duplicates are invoked once for each time they appear in the invocation list. Delegates are immutable; once created, the invocation list of a delegate does not change."

if (whatever != null) whatever(); looks like it ensures that whatever is never null when whatever() is called, but it doesn't actually ensure that in a threaded scenario. A different thread can set whatever = null between the check and the call.

Foo temp = whatever;
if (temp != null) temp();

This code removes the possibility of the null dereference, since temp is a local and will therefore never be modified by a different thread. So it does prevent a race condition. It doesn't prevent all the relevant race conditions though. Eric Lippert did a more elaborate discussion of some other problems with the code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!