对象引用相关资源未被处置

时间:2016-10-20 04:06:21

标签: c#

我收到以下代码的静态代码分析错误

'dsAlertsPointData'引用的对象丢失,但相关资源未被丢弃。

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]);
        }
    }

这是什么决议?谢谢!

1 个答案:

答案 0 :(得分:1)

使用using块来处置dsAlertsPointData。它将在using块结束时释放它所拥有的资源。

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]);
    }
}