c# - 委托(delegate)在 c# 中不可变的目的是什么?

标签 c# delegates

我在看一本图解C#2012的Combining Delegates一节中点没注意到?委托(delegate)的目的是不可变的。

Combining Delegates All the delegates you’ve seen so far have had only a single method in their invocation lists. Delegates can be “combined” by using the addition operator. The result of the operation is the creation of a new delegate, with an invocation list that is the concatenation of copies of the invocation lists of the two operand delegates. For example, the following code creates three delegates. The third delegate is created from the combination of the first two.

MyDel delA = myInstObj.MyM1;
MyDel delB = SClass.OtherM2;
MyDel delC = delA + delB; // Has combined invocation list

Although the term combining delegates might give the impression that the operand delegates are modified, they are not changed at all. In fact, delegates are immutable. After a delegate object is created, it cannot be changed. Figure 15-6 illustrates the results of the preceding code. Notice that the operand delegates remain unchanged.

enter image description here

最佳答案

线程安全和速度是这里的主要关注点。委托(delegate)更新不是原子的,它需要更新 6 个字段和一个列表。使其成为原子以使其不会被破坏需要一个锁,对于这样一个很少需要线程安全的基本操作来说太昂贵了。

通过使其不可变,委托(delegate)对象不会被破坏,因为它总是在一个还没有人引用的对象上设置字段。重新分配委托(delegate)对象引用是原子的,这是基本的 .NET 内存模型保证。所以不再需要锁了。代价是内存使用效率较低,这是一个小惩罚。

请记住,线程安全委托(delegate)更新不会自动使您的代码也成为线程安全的。 test-and-fire 代码需要复制引用以避免 NRE,您可以回调已取消订阅的方法。

关于c# - 委托(delegate)在 c# 中不可变的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968889/

相关文章:

c# - 内存不足异常 - 读取 HttpWebRequest 的大文本文件

c# - 在协程中获取时间

c# - Silverlight HttpWebRequest 安全异常

C# foreach 遍历 Dictionary<String, ObjectType> 中包含的对象的属性

objective-c - NSTableView 中 NSTextFieldCell 的自定义字段编辑器

c# - 为什么这个错误是 "local variable cannot be declared in this scope because it ... is already used"?

c# - 选择不在 C# 程序中使用委托(delegate)

c# - 如何获取组合框中的项目数?

c# - 使用参数安全调用多次调用泛型方法(运行时返回类型)的最佳方法

C# - ThreadPool QueueUserWorkItem 使用?