Removing all event handlers in one go

后端 未结 3 1242
滥情空心
滥情空心 2020-12-19 11:19

Problem: I have a document class which contains a list of objects. These objects raise events such as SolutionExpired, DisplayExpired etc. The docu

3条回答
  •  [愿得一人]
    2020-12-19 12:04

    You can use Delegate.RemoveAll(). (The part you're interested in is in button2_Click)

    public void Form_Load(object sender, EventArgs e) 
    { 
        button1.Click += new EventHandler(button1_Click);
        button1.Click += new EventHandler(button1_Click);
        button2.Click += new EventHandler(button2_Click);
        TestEvent += new EventHandler(Form_TestEvent);
    }
    event EventHandler TestEvent;
    void OnTestEvent(EventArgs e)
    {
        if (TestEvent != null)
            TestEvent(this, e);
    }
    void Form_TestEvent(object sender, EventArgs e)
    {
        MessageBox.Show("TestEvent fired");
    }
    void button2_Click(object sender, EventArgs e)
    {
        Delegate d = TestEvent as Delegate;
        TestEvent = Delegate.RemoveAll(d, d) as EventHandler;
    }
    void button1_Click(object sender, EventArgs e)
    {
        OnTestEvent(EventArgs.Empty);
    }
    

    You should note that it doesn't alter the contents of the delegates you pass in to it, it returns an altered delegate. Consequently, you won't be able to alter the events on a button you've dropped on a form from the form, as button1.Click can only have += or -= used on it, not =. This won't compile:

    button1.Click = Delegate.RemoveAll(d, d) as EventHandler;
    

    Also, be sure that wherever you're implementing this you're watching out for the potential of race conditions. You could end up with some really strange behavior if you're removing handlers from an event that is being called by another thread!

提交回复
热议问题