复制代表 [英] Copying delegates

查看:84
本文介绍了复制代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在MSDN上的事件上阅读了一页,我遇到了令人困惑的示例代码片段。

I was just reading a page on events on MSDN, and I came across a snippet of example code that is puzzling me.

有问题的代码是这样的:

The code in question is this:

// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
EventHandler<CustomEventArgs> handler = RaiseCustomEvent;

我了解代码的意图,但是我看不到该特定行是如何复制的任何东西。它所做的只是复制 reference ;它实际上不是在复制委托实例的深层副本。因此,这实际上并没有完全阻止比赛条件。

I understand the intentions of the code, but I fail to see how that particular line is making a copy of anything. All it is doing is copying the reference; it's not actually making a deep copy of the delegate instance. So to that end, it doesn't actually prevent the race condition at all.

我在这里错过了明显的东西吗?

Am I missing something obvious here?

推荐答案

代理是不可变的,因此可以保证在该代码中获得的引用不会更改。如果在进行空检查后用户订阅或取消订阅,将创建一个新的委托并将其设置为事件。但是,由于您引用了完全不同的对象并调用了该对象,因此不必担心它为null。

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.

这篇关于复制代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆