获得处置关闭 - 标记方法安全 [英] Access to disposed closure - mark methods as safe

查看:418
本文介绍了获得处置关闭 - 标记方法安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于ReSharper的警告访问布置闭包,通常出现在一个对象后来处置在lambda中使用。 在C#中访问废弃关闭?更详细地讨论了这一点。 / p>

我的问题是:对于采取这样的lamdb并立即执行它们的方法(所以你可以确保他们总是在处理该对象之前执行):



有没有办法将它们标记为安全,以便任何使用该方法的代码不再产生这些警告?



示例:

 使用(var myObject = new MyDisposableObject())
{
DoThisTwice( > myObject.DoSomething());
}

...

void DoThisTwice(Action do)
{
do();
do();
}



DoThisTwice接受委托(或lambda)并同步执行。在方法返回时,将不再执行lambda。只有那时, myObject 被处理,所以我们很好去。我们可以用注释标记调用 DoThisTwice 的行,但是必须使用方法以类似的方式在所有地方执行。相反,我想标记 DoThisTwice 为安全所以Resharper不显示任何警告任何调用方法。

解决方案

您可以使用ReSharper的注释来解决这个问题。 ReSharper没有办法知道封闭将持续多久,例如。它可能被分配给一个字段,因此它警告你可能正在使用将在调用lambda时被处理的东西。



你可以修复它像这样:

  void DoThisTwice([InstantHandle] Action action)
{
action
action();
}

InstantHandle 属性告诉ReSharper该动作立即被调用,不会超出方法的范围。


This is about ReSharper's warning "Access to disposed closure" which usually appears when an object which is later disposed is used in a lambda. Access to disposed closure in C#? discusses this in a bit more detail.

My question is: For methods that take such lamdbas and execute them immediately (so you can be sure they are always executed before the said object is disposed):

Is there a way to mark them as safe, so that any code using that method does no longer produced those warnings?

Example:

using (var myObject = new MyDisposableObject())
{
    DoThisTwice(() => myObject.DoSomething());
}

...

void DoThisTwice(Action do)
{
    do();
    do();
}

DoThisTwice takes a delegate (or a lambda) and executes it synchronously. By the time the method returns, the lambda will no longer be executed. Only then the myObject is disposed, so we are good to go. We could mark the line calling DoThisTwice with a comment, but that has to be done in all places using the method in a similar way. Instead I would like to mark DoThisTwice as safe so Resharper does not display any warnings for any callers of the method.

解决方案

You can use ReSharper's annotations to fix this. ReSharper has no way of knowing how long the closure will last, e.g. it might be assigned to a field, and so it warns you that you might possibly be using something that will be disposed by the time the lambda is called.

You can fix it like this:

void DoThisTwice([InstantHandle] Action action)
{
    action();
    action();
}

The InstantHandle attribute tells ReSharper that the action is called immediately and not stored beyond the scope of the method.

这篇关于获得处置关闭 - 标记方法安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆