Should I Dispose() DataSet and DataTable?

前端 未结 12 1345
清酒与你
清酒与你 2020-11-22 02:45

DataSet and DataTable both implement IDisposable, so, by conventional best practices, I should call their Dispose() methods.

However, from what I\'ve read so far, Da

12条回答
  •  温柔的废话
    2020-11-22 02:59

    And this can be the best/proper way to Dispose and release the memory consumed by DataSet.

    try
        {
            DataSet ds = new DataSet("DS");
            //use table DataTable here
            
        }
        catch {  }
        finally
        {
            if (ds != null)
                    {
                        ds.EnforceConstraints = false;
                        ds.Relations.Clear();
                        int totalCount = ds.Tables.Count;
    
                        for (int i = totalCount - 1; i >= 0; i--)
                        {
                            DataTable td1 = ds.Tables[i];
                            if (td1 != null)
                            {
                                td1.Constraints.Clear();
                                td1.Clear();
                                td1.Dispose();
                                td1 = null;
                            }
                        }
    
                        ds.Tables.Clear();
                        ds.Dispose();
                        ds = null;
                    }
        }
    

提交回复
热议问题