Event Handler removing subscribed function not affected

20 Views Asked by At

In C# TreeView class, I've registered a function for AfterEffectHandler in the form initialization

public Form1(){
    InitializeComponent();
    tree.AfterCheck += NodeChecked_AfterCheck;
}

Now later on the class, there is a manual change to the check boxes that I don't want to recursively be called, so I unregister the function "NodeChecked_AfterCheck" and do what I want and unregister it. For some reason this does not work.


private void UpdateNodeCheckedStatus(TreeNode node, string tagName) {
    tree.AfterCheck -= NodeChecked_AfterCheck; // supposed to be removed here
    if (some condition) {
        node.Checked = true;
        // more code
    } else {
        node.Checked = false;
        // more code
    }
    tree.AfterCheck += NodeChecked_AfterCheck; // supposed to readd here
}

Now this "-= NodeChecked_AfterCheck" does not work.

There is an interesting behaviour, the "AfterCheck" method seems to register this function twice. Because the "-= NodeChecked_AfterCheck" removes the 2nd time I add "+= NodeChecked_AfterCheck" and then re-adds it, so it never fires 3 times. So clearly it sees something different with it being in another function.
But it does not work on the first one, why?! What makes the Added reference on the second "+=" so different that it works and understands to remove it, but not the first one?
This code also does not unsubscribe the function:

private void UpdateNodeCheckedStatus(TreeNode node, string tagName) {
    tree.AfterCheck -= NodeChecked_AfterCheck; // supposed to be removed here
    if (some condition) {
        node.Checked = true;
        // more code
    } else {
        node.Checked = false;
        // more code
    }
}

Now I already have 2 work arounds to the problem (for example adding a boolean at the start of the NodeChecked_AfterCheck function and stop it from executing).
I am not looking for a work around.

I want an answer to why "NodeChecked_AfterCheck" in the constructor is not the same in another function when registering or unregistering it when it is the same name (not passing an action/func pointer) and is the same function (that is part of the same class. There is no reference to it anywhere else in the project).

How can they be different. I've tried to set write AfterCheck = null. But this is not allowed for some reason in C# and there is no .Clear() either.

0

There are 0 best solutions below