我需要退订吗?

时间:2018-10-01 10:15:27

标签: c# .net events lambda anonymous-function

我有以下代码:

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

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

诊断处理器给我以下警告:

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

所以我尝试了解这里出了什么问题。 并尝试找到如何更改代码。

可能解决了该警告:

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);
    //...
}

我还有一个问题-我真的需要在这里退订吗? 因为侦听器只是一个本地对象。

UPD:

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

1 个答案:

答案 0 :(得分:3)

将委托存储在变量中,以便可用于在lambda处理程序中进行订阅和取消订阅。

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);
    //...
}