Access to disposed closure in C#?

后端 未结 3 1517
谎友^
谎友^ 2020-12-03 16:29

I\'m investigating Microsoft enterprise library (data application block) -- The samples sln.

They have a sample of reading data asynchronously ( IA

相关标签:
3条回答
  • 2020-12-03 17:16

    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.

    0 讨论(0)
  • 2020-12-03 17:17

    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);
    
    0 讨论(0)
  • 2020-12-03 17:25

    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.

    0 讨论(0)
提交回复
热议问题