How to ensure an event is only subscribed to once

前端 未结 7 1785
南旧
南旧 2020-11-27 04:20

I would like to ensure that I only subscribe once in a particular class for an event on an instance.

For example I would like to be able to do the following:

7条回答
  •  青春惊慌失措
    2020-11-27 04:51

    I did this recently and I'll just drop it here so it stays:

    private bool subscribed;
    
    if(!subscribed)
    {
        myClass.MyEvent += MyHandler;
        subscribed = true;
    } 
    
    private void MyHandler()
    {
        // Do stuff
        myClass.MyEvent -= MyHandler;
        subscribed = false;
    }
    

提交回复
热议问题