What is the purpose of delegates unchanged in C #?

I read a book illustrating C # 2012 in the section "Combining the delegation point", do not notice what? The appointment of delegates is unchanged.

Consolidating Delegates All the delegates you've seen so far have only one method in their call lists. Delegates can be "combined" using the addition operator. The result of the operation is the creation of a new delegate with a call list, which is the concatenation of copies of the call lists from the two operands of the delegates. For example, the following code creates three delegates. A third delegate is created from a combination of the first two.

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

Although the term for delegates may give the impression that the delegates of the operands are changed, they do not change at all. In fact, delegates are unchanged. After creating a delegate object, it cannot be modified. Figure 15-6 illustrates the results of the preceding code. Note that operand delegates remain unchanged.

enter image description here

+5
source share
2 answers

First of all, safety and flow rate are important here. A delegate update is not atomic; it requires updating 6 fields and a list. To make it atomic so that it cannot be damaged requires blocking, which is too expensive for such a basic operation, which rarely needs to be thread safe.

By making it immutable, the delegate object cannot be damaged, since it always sets the fields for an object that is not yet referenced. Reassigning a reference to a delegate object is an atomic, basic guarantee of the .NET memory model. So there’s no need for a lock anymore. Compromise is a less efficient use of memory, this is a small penalty.

Keep in mind that streaming delegate updates does not automatically make your code thread safe. The verification and security code must copy the link to avoid NRE, and you can call back to a method that has already been unsubscribed.

+7
source

Delegates are pointers to a method, both specific and anonymous (well, even anonymous methods are compiled using some identifier generated by the compiler).

Would it be reasonable that something that points to a particular thing can be changed? I do not think so. Each instance represents a pointer to some method. Do you want to point to another method? Create a new pointer. That is, you create a new delegate.

On the other hand, adding two or more delegates has this result because the + operator can be overloaded . That is, delegates can be part of the addition, but internally + overload creates a new delegate with a call list.

+2
source

Source: https://habr.com/ru/post/1244961/


All Articles