Is it safe to register for a C # event?

in particular, is the operation “+ =” an atom? does it matter if i use the keyword "event" or just a plain old delegate?

with most types, read it, then the + operator, and then write. so it's not atomic. I would like to know if there is a special case for delegates / events.

this code is necessary or redundant:

Action handler;
object lockObj;
public event Action Handler {
    add { lock(lockObj) { handler += value; } }
    remove { lock(lockObj) { handler -= value; } }
}
+4
source share
2 answers

, += -= ( , ). MSDN .NET Matters:

# MyClass, Microsoft® Intermediate Language (MSIL) , 1.

1

class MyClass
{
    private EventHandler _myEvent;

    public event EventHandler MyEvent
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        add 
        { 
            _myEvent = (EventHandler)Delegate.Combine(_myEvent, value);
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        remove 
        { 
            _myEvent = (EventHandler)Delegate.Remove(_myEvent, value); 
        }
    }
    ...
}

[...]

- ( ). 1 , MethodImplAttribute, , .. , , :

add { lock(this) _myEvent += value; } 
remove { lock(this) _myEvent -= value; }
+4

, add - , , .

, , , - , . . .

:

Action temp = Foo;
if (temp != null)
      temp();
+3

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


All Articles