2

我以前从未在这个论坛上发过帖子,但经常用它来研究,但这次我找不到答案……也许我只是措辞不正确。

我在一个我已经工作了一段时间的 Compact Framework 项目中经常使用 SqlCeCommand,并且遇到了许多内存不足的问题,因此我正在尝试更好地优化非托管代码部分。

看看这个:

Dim SQLCmd as SQLCeCommand

SQLCmd = New SQLCeCommand
SQLCmd.Connection = conndb
... Process db stuff

SQLCmd = New SQLCeCommand
SQLCmd.Connection = conndb
... Process db stuff

SQLCmd = New SQLCeCommand
SQLCmd.Connection = conndb
... Process db stuff

SQLCmd.Dispose()

这可以吗,还是每次我在同一个对象上调用 New 时都会丢失内存?我这样做而不是保留对象的相同实例的原因是我不必每次都显式设置 SQLCmd 属性。因为有些可能使用参数,有些可能不使用,所以我认为使用 new 将是一种更简单的方法来确保一切都清楚。

有什么想法或更好的方法来解决这个问题吗?

4

1 回答 1

0

在您的代码中,每次您调用 New 时,先前的引用都会丢失,然后是垃圾收集器工作来释放现在未引用的对象。当垃圾收集器框架决定是时候取回内存时会发生这种情况,因此不会立即发生

为了做得更好,您可以使用Using 语句

Dim SQLCmd as SQLCeCommand 

Using SQLCmd = New SQLCeCommand 
    SQLCmd.Connection = conndb 
    ... Process db stuff 
End Using

Using SQLCmd = New SQLCeCommand 
    SQLCmd.Connection = conndb 
    ... Process db stuff 
End Using

Using SQLCmd = New SQLCeCommand 
    SQLCmd.Connection = conndb 
    ... Process db stuff 
End Using

通过这种方式,您会自动为之前的 SqlCmd 调用 Dispose,并向垃圾收集器发出强烈提示以收集未使用的内存。

来自 MSDN

Managed resources are disposed of by the .NET Framework garbage collector (GC) without any 
extra coding on your part. You do not need a Using block for managed resources. However, 
you can still use a Using block to force the disposal of a managed resource instead of 
waiting for the garbage collector.
于 2012-09-29T12:33:41.343 回答