I\'m investigating Microsoft enterprise library (data application block) -- The samples sln.
They have a sample of reading data asynchronously ( IA
You pass doneWaitingEvent
to a lambda that may extend beyond the scope of the using block. I.e. there's a risk that Dispose
will have been called when the lambda executes.
It yells warning because the engine is not smart enough to figure out that the using block will never be exited before the delegate code completes. That is why this is a warning not a error.
You can safely ignore this warning, you can have resharper suppress the warning by wrapping the lines with special comments
asyncDB.BeginExecuteReader(cmd, asyncResult =>
{
// Lambda expression executed when the data access completes.
// ReSharper disable AccessToDisposedClosure
doneWaitingEvent.Set();
// ReSharper restore AccessToDisposedClosure
try
{
using (IDataReader reader = asyncDB.EndExecuteReader(asyncResult))
{
Console.WriteLine();
Console.WriteLine();
DisplayRowValues(reader);
}
}
catch (Exception ex)
{
Console.WriteLine("Error after data access completed: {0}", ex.Message);
}
finally
{
// ReSharper disable AccessToDisposedClosure
readCompleteEvent.Set();
// ReSharper restore AccessToDisposedClosure
}
}, null);
The reason you see ReSharper's warnings is that ReSharper's code flow analysis engine is not strong enough to see what is going on: they assume that your code could get to the end of the using
clause without doneWaitingEvent
being set, which is not possible due to a while
loop:
while (!doneWaitingEvent.WaitOne(1000)) {
Console.Write("Waiting... ");
}
The loop will keep printing the "Waiting... "
line until doneWaitingEvent.Set();
gets called, preventing your code from reaching the end of the using
block. Same goes for the other warning.
Long story short, this warning can be safely ignored. Add ReSharper's "ignore this warning" comments, and optionally file a bug report with them.