1

Possible Duplicate:
Unsubscribe anonymous method in C# How do I Unregister 'anonymous' event handler

Ok, lets say I have the following code:

    private void AttachEvent(AwesomeObject someObject)
    {
        int id = GetCurrentIdValue();
        someUnknownClass.SomeEvent += () => someObject.CreateAwesomeness(id);
    }

(essentially, I'm just trying to illustrate the need to use a local variable in an event handler as suggested in this thread). From a memory management standpoint, I can't just detach from someUnknownClass.SomeEvent because I don't have a handle on the handler. Further, let's assume someUnknownClass is a third party type, so I can't add any code within that class to detach the event internally as suggested.

My question is, how do I avoid a memory leaks while still being able to use anonymous methods as event handlers?

Community
  • 1
  • 1
Devin
  • 1,014
  • 1
  • 9
  • 28
  • As well as: http://stackoverflow.com/questions/1348150/how-do-i-unregister-anonymous-event-handler and http://stackoverflow.com/questions/2051357/c-sharp-adding-and-removing-anonymous-event-handler and many others. – Oded Apr 11 '12 at 20:26
  • Specifically with lambdas, answer here: http://stackoverflow.com/a/1362244/1583 – Oded Apr 11 '12 at 20:28

1 Answers1

0

It's not possible, not in the way you use them. What you can do is assign that method to a variable and after use that variable to +- from event. But in this way you will loose "natural" feeling that closures usually give you .

Tigran
  • 61,654
  • 8
  • 86
  • 123