简体   繁体   中英

Do I need to unsubscribe?

I have the following code:

public void UnPublishDatabases(IReadOnlyCollection<IPublishedDatabase> sqlDatabases)
{
    var listener = new UnpublishDatabaseListener();
    listener.DatabaseUnpublished += db =>
    {
        OnDatabaseUnpublished(db); 
        listener.DatabaseUnpublished -= OnDatabaseUnpublished;
    };

    _publishController.Unpublish(sqlDatabases, listener);
    //...
}

And diagnostic processor gives me the following warning:

Event 'listener.DatabaseUnpublished' should not be subscribed with the same 'listener.DatabaseUnpublished' object.

So I try to understand what is wrong here. And try to find how to change the code.

Probably it solves the warning:

public void UnPublishDatabases(IReadOnlyCollection<IPublishedDatabase> sqlDatabases)
{
    var listener = new UnpublishDatabaseListener();
    //save ref
    var listenerCopy = listener;
    listener.DatabaseUnpublished += db =>
    {
        OnDatabaseUnpublished(db); 
        //use it
        listenerCopy.DatabaseUnpublished -= OnDatabaseUnpublished;
    };

    _publishController.Unpublish(sqlDatabases, listener);
    //...
}

Also I have a question - do I really need to unsubscribe here ? Because listener is just a local object.

UPD:

public class UnpublishDatabaseListener
{
    public event Action<IPublishedDatabase> DatabaseUnpublished;
    //...
}

Store the delegate in a variable so that it can be used to subscribe and unsubscribe in the lambda handler.

public void UnPublishDatabases(IReadOnlyCollection<IPublishedDatabase> sqlDatabases) {
    var listener = new UnpublishDatabaseListener();
    Action<IPublishedDatabase> handler = delegate { };
    handler = db => {
        OnDatabaseUnpublished(db); 
        //unsubscribe
        listner.DatabaseUnpublished -= handler;
    };
    //subscribe
    listener.DatabaseUnpublished += handler;

    _publishController.Unpublish(sqlDatabases, listener);
    //...
}

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