C # Why is my lock statement hanging?

I read several tutorials on how to create custem event accessors. This is the code I have:

event ControlNameChangeHandler IProcessBlock.OnControlNameChanged { add { lock (ControlNameChanged) { ControlNameChanged += value; } } remove { lock (ControlNameChanged) { ControlNameChanged -= value; } } } 

The moment the code reaches lock(ControlNameChanged) in the incremental statament, nothing happens. The code no longer works. However, my application is still working. It does not freeze or something like that.

What's wrong?

+4
source share
3 answers

Somehow, someone is holding a castle. You should not use instances of multicast delegates or events to block, and you should also not use public elements because you cannot control who is blocked and when.

Therefore, I would use a separate lock object similar to this:

 private readonly object controlNameChangedSync = new object(); event ControlNameChangeHandler IProcessBlock.OnControlNameChanged { add { lock (controlNameChangedSync) { ControlNameChanged += value; } } remove { lock (controlNameChangedSync) { ControlNameChanged -= value; } } } 

Note. the event reference changes when += or -= is executed in the delegate.

+13
source

Your code is equivalent

 event ControlNameChangeHandler IProcessBlock.OnControlNameChanged { add { try { Monitor.Enter(ControlNameChanged); ControlNameChanged = ControlNameChanged + value; } finally { Monitor.Exit(ControlNameChanged); } } remove { try { Monitor.Enter(ControlNameChanged); ControlNameChanged = ControlNameChanged - value; } finally { Monitor.Exit(ControlNameChanged); } } } 

Note that the Exit object is different from what you entered. This means that you have one captured lock that is never released, and one lock is released, but never removed. You should change your code to this:

 private object padlock = new object(); event ControlNameChangeHandler IProcessBlock.OnControlNameChanged { add { lock (padlock) { ControlNameChanged += value; } } remove { lock (padlock) { ControlNameChanged -= value; } } } 
+8
source

The += and -= operators change the delegate. Thus, your Add and Remove methods are blocked on different objects each time, and you don’t have synchronization at all.

Now this will not explain the lock, but your question is not very clear on what is actually happening. I expected the program to perform "normally" with the possibility of a race.

+4
source

All Articles