Clean up locking implementation in WeakEventHandlerBase #3
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
The
WeakEventHandlerBaseneeds to protect all access to the_handlerslist with the_lockto avoid state corruption.Additionally, the handlers should be executed whilst the lock is not held, to avoid deadlocks if a handler attempts to call a method on the event object.
Type of Change
Checklist
main)..editorconfig)Testing Instructions
With the current code, a handler which attempts to modify the event object could result in corrupted state. At the very least, any attempt to modify the handlers list from a handler would result in an
InvalidOperationException:The simplistic solution is to wrap every access to the
_handlerslist in the lock. However, this would then result in a deadlock, since the handler is executed whilst the lock is already held, and theSemaphoreSlimdoes not support reentrancy.Therefore, the actual solution is to also ensure that the handlers are invoked whilst the lock is not held. This involves taking a copy of the handlers list within the lock, and then operating on it outside of the lock.