3 ms·
It's a "feature" on the language, like others said below. The codebase I work with has had many pathological crashes due to this behavior. So basically in C#
by olvy0 4y ago
It's a "feature" on the language, like others said below.
The codebase I work with has had many pathological crashes due to this behavior.
So basically in C# when you use += to subscribe to events, in a big system where lifetimes of objects are independent of each other, you're back to a C/C++ mindset where you should check you have a -= call for the subscribed object when the subscribing object is about to run out of scope. Else you get random crashes, when you get events delivered to an object that should have been dead.
This is one of the reasons I don't like "event" and += in C#. It's a leaky abstraction, like you said.
There's WeakEventManager [0] but that's available only in "classic" dotnet framework (and in "new" dotnet but only if you're targeting Windows) since it lives in the WPF namespace. It can be used outside of it, but you still take a dependency on System.Windows.
There are some other bespoke solutions too.
There's an open issue on the dotnet repo to add a weak event manager to the standard libs [1]. It's very well worth reading through it, it also has links to the other bespoke solutions available.
[0] https://docs.microsoft.com/en-us/dotnet/api/system.windows.weakeventmanager?view=windowsdesktop-6.0 https://docs.microsoft.com/en-us/dotnet/api/system.windows.w...
[1] https://github.com/dotnet/runtime/issues/18645 https://github.com/dotnet/runtime/issues/18645