osp*_*p70 1 .net vb.net garbage-collection memory-leaks
基本上我想知道在VB.NET 2005中是否使用sqlcommand然后使用NEW重用它是错误的.它会导致内存泄漏吗?
例如:
try
dim mySQL as new sqlcommand(sSQL, cnInput)
// do a sql execute and read the data
mySQL = new sqlcommand(sSQLdifferent, cnInput)
// do sql execute and read the data
catch ...
finally
if mysql isnot nothing then
mysql.dispose
mysql = nothing
end if
Run Code Online (Sandbox Code Playgroud)
编辑:把try catch放入以避免关于不使用它们的评论
只是为了扩展Longhorn213所说的内容,这里是它的代码:
Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)
' do stuff'
End Using
Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput)
' do other stuff'
End Using
Run Code Online (Sandbox Code Playgroud)
(编辑)就像一个FYI一样,使用自动包装try/finally周围的代码块,该代码块在创建它的变量上调用Dispose方法.因此,这是确保释放资源的简便方法.http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx