We came across an issue where an object was not being disposed. After some tracking down it turns out that it was due to the compiler generating a static lambda.
The class has an event and the lambda was being defined for the event. As it just used the parameters and local fields the compiler optimised this to be static. This means that when the object is finished with the event still points to the static lambda and can’t be disposed, so it gets left around.
Also as it was a lambda expression it is not possible to call the –= to remove it.
Obviously over time and depending on the usage of the class this could lead to a lot of these being left hanging around and not being garbage collected.
This can easily be solved by using a method instead however is the “optimisation” of compiling a lambda to a static on an event a bug or a feature?