Disposing data table?

非 Y 不嫁゛ 提交于 2019-12-11 18:56:53

问题


I was reading this msdn article today and I am curious about finally part with disposing datatable. Is that really necessary? why should we dispose a datatable? If I exit the function or sub, is it not releasing the resources?

Explanation in the article is; Dispose of the temporary data tables to release the resources.

Private Sub UpdateDB()
Dim deletedChildRecords As NorthwindDataSet.OrdersDataTable = _
    CType(NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Deleted), NorthwindDataSet.OrdersDataTable)

Dim newChildRecords As NorthwindDataSet.OrdersDataTable = _
    CType(NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Added), NorthwindDataSet.OrdersDataTable)

Dim modifiedChildRecords As NorthwindDataSet.OrdersDataTable = _
    CType(NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Modified), NorthwindDataSet.OrdersDataTable)

Try
    If deletedChildRecords IsNot Nothing Then
        OrdersTableAdapter.Update(deletedChildRecords)
    End If

    CustomersTableAdapter.Update(NorthwindDataSet.Customers)

    If newChildRecords IsNot Nothing Then
        OrdersTableAdapter.Update(newChildRecords)
    End If

    If modifiedChildRecords IsNot Nothing Then
        OrdersTableAdapter.Update(modifiedChildRecords)
    End If

    NorthwindDataSet.AcceptChanges()

Catch ex As Exception
    MessageBox.Show("An error occurred during the update process")
    ' Add code to handle error here.

Finally
    If deletedChildRecords IsNot Nothing Then
        deletedChildRecords.Dispose()
    End If

    If newChildRecords IsNot Nothing Then
        newChildRecords.Dispose()
    End If

    If modifiedChildRecords IsNot Nothing Then
        modifiedChildRecords.Dispose()
    End If

End Try
End Sub

回答1:


To answer your question, is it necessary to dispose a datatable? The concensus is no, here's my thought.

Setting things to null or nothing doesn't remove the memory used by the instance of the object. Neither does dispose. The GC does, when it runs. Remember, when you have a reference variable, you have a pointer to an object. When you repoint that variable to a null address, it doesn't delete the data at the previous address, nor does it free the memory.

Basically, dispose is useful for preparing your objects for being destroyed, but it doesn't actually release the memory used by the object. If you're dealing with resources that need cleaning up, like open streams, database connections, things like that, dispose is great.



来源:https://stackoverflow.com/questions/24285616/disposing-data-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!