在代理

时间:2016-02-19 08:39:10

标签: c# resharper

我正在使用TaskCompletionSource。我在对象上注册事件,但是当我尝试在我的事件方法中取消注册时,resharper用注释强调它:访问修改后的闭包。

这是我的代码

var taskCompletionSource = new TaskCompletionSource<bool>();
OnConnectionStateChangedInd handlerConnectionStateChangedInd = null;
OnBootCompletedCnfCallback handlerBootCompletedCnfCallback = null;

handlerConnectionStateChangedInd = (id, method, addr, port, nick) =>
{
    _corePttObject.onConnectionStateChangedInd -= handlerConnectionStateChangedInd;
    _connectionState = id;

    taskCompletionSource.SetResult(true);
};
_corePttObject.onConnectionStateChangedInd += handlerConnectionStateChangedInd;

这一行标有下划线:

  

_corePttObject.onConnectionStateChangedInd - = handlerConnectionStateChangedInd;

以下是我对方法的完整定义:

public Task<LoginResult> LoginAsync(string address)
    {
        var taskCompletionSource = new TaskCompletionSource<LoginResult>();
        OnUserAcceptCertWithNamePasswInd handlerAcceptCertWithNamePasswInd = null;
        OnAppExLoginProtocolServiceCnf handlerAppExLoginProtocolServiceCnf = null;
        handlerAcceptCertWithNamePasswInd = (cert, caCert, rootCert, hash, pos, data) =>
        {
            var loginCompletedArgs = new LoginResult
            {
                SvrCertificate = ParseCertificate(cert),
                CaCertificate = ParseCertificate(caCert),
                RootCertificate = ParseCertificate(rootCert),
                CertificateHash = hash,
                GridPosition = pos,
                GridData = data
            };
            _corePttObject.onUserAcceptCertWithNamePasswInd -= handlerAcceptCertWithNamePasswInd;
            taskCompletionSource.SetResult(loginCompletedArgs);
        };

        handlerAppExLoginProtocolServiceCnf = (nick, result, cause, link) =>
        {
            _corePttObject.onAppExLoginProtocolServiceCnf -= handlerAppExLoginProtocolServiceCnf;
        };

        _corePttObject.onAppExLoginProtocolServiceCnf += handlerAppExLoginProtocolServiceCnf;
        _corePttObject.onUserAcceptCertWithNamePasswInd += handlerAcceptCertWithNamePasswInd;
        //TODO: read id.
        _corePttObject.Login(address, true, "ID");

        return taskCompletionSource.Task;
    }

2 个答案:

答案 0 :(得分:1)

如果单击灯泡建议,则会出现“为什么ReSharper建议这样”的选项。如果您点击它,则会转到此有用的explanation

我需要更多的背景来判断这个潜在的陷阱在你的特定情况下是否真的会伤害你。

您还可以查看this answer here

答案 1 :(得分:1)

此警告的原因是:对于handlerConnectionStateChangedInd,您声明了一种匿名方法 - 在最终执行时 - 将访问/更改_corePttObject.onConnectionStateChangedInd

然后,此声明之后,更改 _corePttObject.onConnectionStateChangedInd已在此行中:

_corePttObject.onConnectionStateChangedInd += handlerConnectionStateChangedInd;

因此,ReSharper警告您,在您声明_corePttObject.onConnectionStateChangedInd的时间与执行时间之间,值handlerConnectionStateChangedInd会有所不同。