简体   繁体   中英

Unsubscribing events in case variable closure

I'm always try to unsubscribe events where it possible and may. In case when variable closure happen I do the following :

int someVar;

EventHandler moveCompleted = null;
moveCompleted = delegate(object sender, EventArgs e)
{
    //...
    //here is variable closure
    someVar = 5;
    //...
    moveStoryboard.Completed -= moveCompleted;
};

moveStoryboard.Completed += moveCompleted;

But I don't want to use anonymous method and I think this is not good way. Please give me some advice or code samples.

Thanks in advance.

If you don't want to use an anonymous function, it's much easier:

moveStoryboard.Completed += HandleStoryboardCompleted;

...

private void HandleStoryboardCompleted(object sender, EventArgs e)
{
    // Do stuff...
    moveStoryboard.Completed -= HandleStoryboardCompleted;
}

That will actually create another instance of EventHandler each time the method is called, but because that instance will be equal to the one used to subscribe (same method with the same target) it will be fine to use for unsubscription.

whats wrong with:

class MyClass
{
    public event EventHandler MyEvent;

    public MyClass()
    {
        MyEvent += OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
    }

    protected void OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice(object sender, EventArgs e)
    {
        MyEvent -= OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM