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:
The
InstantHandle
attribute tells ReSharper that the action is called immediately and not stored beyond the scope of the method.