Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I want to use the OnCreateFeature-Event to combine it with other actions. So I use

Events.OnCreateFeature += delegate(IObject obj) { LoopTools_OnCreateFeature(obj); };

to listen to this event. That works very well.

But how can I stop listening? I tried

Events.OnCreateFeature -= delegate(IObject obj) { LoopTools_OnCreateFeature(obj); };

but this didn't release the event. So when I looped through some sweeps, it happened that I have wired the event two or more times and the corresponding actions are done to often. I also tried

Events.OnCreateFeature -= LoopTools_OnCreateFeature;

but that has the same effect. What am I doing wrong?

I'm thankful for any suggestions.

share|improve this question

1 Answer 1

In your code, you are subscribing to an event using an anonymous method delegate. When you need to unsubscribe from an event, it is generally easier and more readable to use non-anonymous methods (note this is C# 3 or higher code, C# 2 would need to be a bit more verbose):

// subscribe
Events.OnCreateFeature += OnCreateFeature;

// unsubscribe
Events.OnCreateFeature -= OnCreateFeature;

The method that gets called when the event is raised then looks like:

public void OnCreateFeature(IObject object)
{
   LoopTools_OnCreateFeature(obj);
}

But anonymous methods can be unsubscribed as well, you just need to keep the reference to the delegate around (I assume your OnCreateFeature event comes from IEditEvents):

IEditEvents_OnCreateFeatureEventHandler onCreateFeatureDelegate = delegate(IObject obj) { LoopTools_OnCreateFeature(obj); };

// subscribe
Events.OnCreateFeature += onCreateFeatureDelegate;

// unsubscribe
Events.OnCreateFeature -= onCreateFeatureDelegate;

As you probably see by now, you'd most likely need to keep the onCreateFeatureDelegate reference as a class field in contrast to a local variable as shown in the sample. That's why I believe the first approach is more readable and does not clutter your code excessively.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.