简体   繁体   中英

Object is not disposed along all execution paths

I have the following code.

private DataTable LoadSMSCellProviders()
{
    string sqlQuery = "Select * from SMSAddress";
    DataTable dt = new DataTable();
    using (SqlConnection conn = new SqlConnection(Utility.ConnString))
    {
        using (SqlCommand command = new SqlCommand(sqlQuery, conn))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            adapter.Fill(dt);
            return dt;
        }
    }
}

The Microsoft Code Analysis is telling me that dt is not disposed along all execution paths, but I am not sure how to correct this. If I try to call dispose on it before the return , it will return a null value, and if I try to do it at the end of the method, the code is never reached...

What am I missing here?

This is the message from the analysis tool:

warning : CA2000 : Microsoft.Reliability : In method 'xx()', object 'dt' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'dt' before all references to it are out of scope.

You need to dispose of it when an exception occurs. Like this.

private DataTable LoadSMSCellProviders()
{
    string sqlQuery = "Select * from SMSAddress";
    DataTable dt = null;
    try
    {
        dt = new DataTable();
        using (SqlConnection conn = new SqlConnection(Utility.ConnString))
        {
            using (SqlCommand command = new SqlCommand(sqlQuery, conn))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(dt);
                return dt;
            }
        }
    }
    catch
    {
        if(dt != null)
            dt.Dispose();
        throw;
    }
}

The idea is that if an exception occurs then there is no way to dispose of the DataTable because it will not be passed back to the caller. So, this is the pattern that will make code analysis happy.

Fire the tool. DataTables do not need to be disposed. They are IDisposable because they inherit IComponent, but their Dispose() method does nothing. I find it disgusting that MS's own tool does not know this.

The Code Analysis is warning you that this object may not get disposed. As @juharr rightly suggests, you should neutralise the code path where an exception occurs, otherwise the object won't get returned and it won't be explicitly disposed of. This will get rid of the warning.

Check the @juharr answer, and also after you use the Datatable and you don't need it any more just do

using(dt){}

and it will dispose it for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM