views:

1474

answers:

4

Hi Guys,
I have the following code:

public List<IWFResourceInstance> FindStepsByType(IWFResource res)  
        {  
            List<IWFResourceInstance> retval = new List<IWFResourceInstance>();  
            this.FoundStep += delegate(object sender, WalkerStepEventArgs e)   
            {   
                if (e.Step.ResourceType == res) retval.Add(e.Step);   
            };  

            this.Start();  

            return retval;
        }

Notice, how i register my event member (FoundStep) to local in-place anonymous function.
My question is: when the function 'FindStepByType' will end - will the anonymous function be removed automatically from the delegate list of the event or i have to manually remove it before steping out the function (and how do i do that?)
hope my question was clear.

thanks a lot!
Adi Barda

+4  A: 

No, it will not be removed automatically. In this sense, there's not a difference between an anonymous method and a "normal" method. If you want, you should manually unsubscribe from the event.

Actually, it'll capture other variables (e.g. res in your example) and keep them alive (prevents garbage collector from collecting them) too.

Mehrdad Afshari
Isn't it just the same as using predicates? When i use predicates i do not free the predicate delegate.
Adi Barda
Predicates are not saved anywhere, but here, you are subscribing to an event. As long as the object containing the event is alive, it'll hold a reference to your delegate and indirectly to its variables. When you pass say, `.Where(x => x.Hidden)` to some method, the method will do the work with it and throw it away (it's just a local variable as far as the `Where` method is concerned. This is not true for your case. Additionally, if `Where` did store it somewhere, you should have worried about this too.
Mehrdad Afshari
+1  A: 

When using an anonymous delegate (or a lambda expression) to subscribe to an event does not allow you to easily unsubscribe from that event later. An event handler is never automatically unsubscribed.

If you look at your code, even though you declare and subscribe to the event in a function, the event you are subscribing to is on the class, so once subscribed it will always be subscribed even after the function exits. The other important thing to realize is that each time this function is called, it will subscribe to the event again. This is perfectly legal since events are essentially multicast delegates and allow multiple subscribers. (This may or may not be what you intend.)

In order to unsubscribe from the delegate before you exit the function, you would need to store the anonymous delegate in a delegate variable and add the delegate to the event. You should then be able to remove the delegate from the event before the function exits.

For these reasons, if you will have to unsubscribe from the event at some later point it is not recommended to use anonymous delegates. See How to: Subscribe to and Unsubscribe from Events (C# Programming Guide) (specifically the section titled "To subscribe to events by using an anonymous method").

Scott Dorman
+4  A: 

Your code has a few problems (some you and others have identified):

  • The anonymous delegate cannot be removed from the event as coded.
  • The anonymous delegate will live longer than the life of the method calling it because you've added it to FoundStep which is a member of this.
  • Every entry into FindStepsByType adds another anonymous delegate to FoundStep.
  • The anonymous delegate is a closure and effectively extends the lifetime of retval, so even if you stop referencing retval elsewhere in your code, it's still held by the anonymous delegate.

To fix this, and still use an anonymous delegate, assign it to a local variable, and then remove the handler inside a finally block (necessary in case the handler throws an exception):

  public List<IWFResourceInstance> FindStepsByType(IWFResource res)
  {
     List<IWFResourceInstance> retval = new List<IWFResourceInstance>();
     EventHandler<WalkerStepEventArgs> handler = (sender, e) =>
     {
        if (e.Step.ResourceType == res) retval.Add(e.Step);
     };

     this.FoundStep += handler;

     try
     {
        this.Start();
     }
     finally
     {
        this.FoundStep -= handler;
     }

     return retval;
  }
Kit
A: 

Below is approach about how unsubscribe event in anonymous method:L

DispatcherTimer _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromMilliseconds(1000); EventHandler handler = null;

        int i = 0;

        _timer.Tick += handler = new EventHandler(delegate(object s, EventArgs ev)
        {
            i++;
            if(i==10)
                _timer.Tick -= handler;

        });

        _timer.Start();
Amit