If I register an event in C # while sending it, am I sure I won’t be called again during this sending?

In C #, I sometimes have to register a method for an event in the middle of sending the same event. For example, if I have a class that translates states based on successive dispatches of the same event, I might need the first state handler to unregister and register the second handler. However, I do not want the second handler to be sent before the next event trigger.

The good news is that it looks like Microsoft's C # implementation is behaving that way. Sack event registration syntax is replaced by a call to System.Delegate.Combine, which simply combines the current list of calls and the new method into a separate list and assigns an event property to it. This gives me exactly the behavior I want.

So my question is: is this guaranteed behavior by locale? I like to be able to run my C # code on other platforms under mono and, as a rule, I want to make sure that I do not make assumptions about the language standard based on its implementation.

I could not find the final information about MSDN.

If you need a specific example of what I'm saying, here is an example:

delegate void TestDelegate(); static event TestDelegate TestEvent; static void Main (string[] args) { TestEvent += TestDelegateInstanceFirst; TestEvent(); TestEvent(); } static void TestDelegateInstanceFirst () { Console.WriteLine("First"); TestEvent += TestDelegateInstanceSecond; } static void TestDelegateInstanceSecond () { Console.WriteLine("Second"); } 

At least on Windows, the output is:

 First First Second 
+4
source share
1 answer

Yes, it is guaranteed.

From the single C # 3.0 specification, section 15.1:

However, when two non-empty delegate examples are combined, their call lists are combined in the order of the left operand then the right operand - to create a new call list that contains two or more entries.

Pay attention to the "new call list." And again in section 15.3:

After an instance is created, delegated instances always refer to the same target object and method. Remember, when two delegates merge, or are removed from another, a new delegate results with its own call list; Delegated or deleted delegate invitation lists remain unchanged.

Finally, the MSDN for System.Delegate states:

Delegates are immutable; after creation, the delegate call list does not change.

I suspect there is something in the CLI specification - I will check if you want, but I hope these three gave you enough confidence :)

+8
source

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


All Articles