0

I am getting static code analysis error for below code,

Object referenced by 'dsAlertsPointData' is lost, but related resource are not disposed.

internal static void PrepareDataTables(List<AlertsData> processedAlertsData, out DataTable dtAlertsData, out DataSet dsMergedAlertsPointData)
    {
        var dsAlertsPointData = new DataSet();
        dsMergedAlertsPointData = new DataSet();
        dsMergedAlertsPointData.Tables.Add("AlertsPointData");

        dtAlertsData = processedAlertsData.ToDataTable();

        foreach (var singleAlert in processedAlertsData)
        {
            if (singleAlert.AlertsPointsData.Count > 0)
                dsAlertsPointData.Tables.Add(singleAlert.AlertsPointsData.ToDataTable());
        }

        for (var i = 0; i < dsAlertsPointData.Tables.Count; i++)
        {
            dsMergedAlertsPointData.Tables["AlertsPointData"].Merge(dsAlertsPointData.Tables[i]);
        }
    }

What is the resolution for this?? Thanks!

user2994834
  • 387
  • 1
  • 4
  • 14
  • Don't write out DataTable this line doesn't have any meaning. DataTable is class so you are transferring the value of the reference. Show the method which calls PrepareDataTable and tell us on which line the error happen. – mybirthname Oct 20 '16 at 04:54

1 Answers1

1

Use using block to dispose dsAlertsPointData. It will free the resources held by it at the end of using block.

using (var dsAlertsPointData = new DataSet())
{
    dsMergedAlertsPointData = new DataSet();
    dsMergedAlertsPointData.Tables.Add("AlertsPointData");

    dtAlertsData = processedAlertsData.ToDataTable();

    foreach (var singleAlert in processedAlertsData)
    {
        if (singleAlert.AlertsPointsData.Count > 0)
            dsAlertsPointData.Tables.Add(singleAlert.AlertsPointsData.ToDataTable());
    }

    for (var i = 0; i < dsAlertsPointData.Tables.Count; i++)
    {
        dsMergedAlertsPointData.Tables["AlertsPointData"].Merge(dsAlertsPointData.Tables[i]);
    }
}
Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20
  • thanks, but still the same error, the related resource are not disposed. – user2994834 Oct 20 '16 at 04:33
  • add `using` blocks for `dsMergedAlertsPointData` and `dtAlertsData` as well – Akshey Bhat Oct 20 '16 at 04:37
  • I don't see any point to use Dispose on DataSet. DataSet are not IDisposable objects. – mybirthname Oct 20 '16 at 04:52
  • `DataSet` class derives from `MarshalByValueComponent` class which is an IDisposable object. You can call `Dispose` method for a `DataSet`. – Akshey Bhat Oct 20 '16 at 04:55
  • The Dispose method in DataSet exists ONLY because of side effect of inheritance-- in other words, it doesn't actually do anything useful in the finalization.Here a question to read: http://stackoverflow.com/questions/913228/should-i-dispose-dataset-and-datatable – mybirthname Oct 20 '16 at 05:30