访问委托中修改的闭包
本文关键字:闭包 修改 访问 | 更新日期: 2023-09-27 18:35:17
我正在使用TaskCompletionSource。我在对象上注册事件,但是当我尝试在我的事件方法中取消注册时,锐化器会用注释为它加下划线:访问修改后的闭包。
这是我的代码
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;
}
此警告的原因是:对于handlerConnectionStateChangedInd
,您声明了一个匿名方法 - 最终执行时 - 将访问/更改_corePttObject.onConnectionStateChangedInd
。
然后,在此声明之后,更改_corePttObject.onConnectionStateChangedInd
已在此行中:
_corePttObject.onConnectionStateChangedInd += handlerConnectionStateChangedInd;
因此,ReSharper警告您,_corePttObject.onConnectionStateChangedInd
值在声明handlerConnectionStateChangedInd
和执行时间之间是不同的。
如果您单击灯泡建议,将有一个选项"为什么 ReSharper 建议这个"。如果您单击它,它将带您进入这个有用的解释。
我需要更多的背景来判断这个潜在的陷阱是否真的会在你的特定情况下伤害你。
你也可以在这里查看这个答案。