我如何实现我的代码,以防止对象处置异常 [英] How do I implement my code so that to prevent getting object disposed exception
问题描述
嗨。
如果我运行程序的话,我的应用程序中的随机对象处理异常有5次。每次运行程序时都不会抛出异常。
stacktrace说在file1 = no的行发生异常。
我如何解决这个错误的行为?
更好的方法来实现代码?
Hi.
I got randomly Object disposed exception in my application 1 out of 5 times if I ran the program. It does not throw exceptions every time i ran the program.
stacktrace says the exception is occured at the line where file1 = nothing.
How do i solve this erratick behaviour ?
Better way to implemt the code?
Dim sbSQL As New StringBuilder
sbSQL.Append("SELECT Item_Id from MyTableA")
Dim ds1 As New DataSet
Using daFindOutdated As New SqlDataAdapter(sbSQL.ToString, cn)
daFindOutdated.Fill(ds1)
End Using
Dim sbPath As New StringBuilder
For Each row As DataRow In ds1.Tables(0).Rows
sbPath.Append(ConfigurationManager.AppSettings("ZipFilePath") & "TBL" & row.Item("Item_ID").ToString.PadLeft(5, "0") & ".zip")
If File.Exists(sbPath.ToString) Then
Dim zip As New ZipArchive(New DiskFile(sbPath.ToString))
Dim folder1 As AbstractFolder = zip.GetFolder("\Item\File\")
Dim file1 As AbstractFile = folder1.GetFile("Tbl.cpf")
Using sw1 As New StreamWriter(file1.OpenWrite(True))
sw1.AutoFlush = True
sw1.WriteLine("")
sw1.Close()
file1 = Nothing
End Using
Dim folder2 As AbstractFolder = zip.GetFolder("\Item\File\")
Dim file2 As AbstractFile = folder2.GetFile("Tbl.cmp")
Using sw2 As New StreamWriter(file2.OpenWrite(True))
sw2.AutoFlush = True
sw2.WriteLine("")
sw2.Close()
file2 = Nothing
End Using
Dim folder3 As AbstractFolder = zip.GetFolder("\Item\File\")
Dim file3 As AbstractFile = folder3.GetFile("Tbl.upc")
Using sw3 As New StreamWriter(file3.OpenWrite(True))
sw3.AutoFlush = True
sw3.WriteLine("")
sw3.Close()
file3 = Nothing
End Using
zip = Nothing
End If
sbPath.Length = 0
Next
我尝试了什么:
我试图使用System。 Threading.Thread.Sleep(1000)之前它没有赋予file1或zip对象。但我不认为这是好主意,或者它会不会有所帮助。程序更有可能迭代10000次以上来创建这三个不同的zip文件。请帮帮我。谢谢。
What I have tried:
I tried to use System.Threading.Thread.Sleep(1000) before it assigns nothing to file1 or zip object. But I do not think this is good idea or it will or it will not help. There is more likely the program iterates more than 10000 times to create these three different zip files. Please help me out. Thank you.
推荐答案
为什么要写
Why do you write
sw1.Close()
file1 = Nothing
我不熟悉visual basic但使用operator(调用StreamWritter的Dispose())应该关闭并处理file1。
I am not familiar with visual basic but using operator (calling Dispose() of StreamWritter) should close and dispose the file1.
这篇关于我如何实现我的代码,以防止对象处置异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!