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.