我正在使用一個文件。這是代碼:爲什麼不在.net中立即關閉文件?
Private Sub WriteXml(ByVal txtName As String)
If Not Directory.Exists("GraphXml") Then
Directory.CreateDirectory("GraphXml")
End If
_fileName = "GraphXml\Graph_" & txtName & ".xml"
Dim checkCondition As Boolean = False
_file = My.Computer.FileSystem.OpenTextFileWriter(_fileName, False)
_file.WriteLine("<?xml version=""1.0"" encoding=""UTF-8""?>")
_file.WriteLine("<n0>")
DepthFirstSearch(StaticService.AllNodes(0))
_file.WriteLine("</n0>")
_file.Close()
_file.Dispose()
End Sub
單擊按鈕時調用此方法。如果我每2秒鐘點擊1次,則會出現錯誤:「另一個進程使用文件」。我無法理解這個問題,因爲我使用了file.close。我認爲這可能與線程問題有關,我問了這個問題鏈接:我試着用線程。這樣的代碼:
when a method is called , which thread will be run in c# and java?
,我試圖與線程。代碼是這樣的:
Dim thread As Threading.Thread = Nothing
Public Sub CreateXml()
'cok hızlı tıklandıgı zaman xml olusturmak için çalışan thread önceki thread in file.close yapmasını bekler
' If Not checkThread Then
Dim txtName As String = InputTxt.Items(InputTxt.SelectedIndex)
txtName = txtName.Substring(0, txtName.IndexOf("."))
While Not IsNothing(thread) AndAlso thread.IsAlive
Dim a = ""
' wait loop
End While
thread = New Threading.Thread(Sub() WriteXml(txtName))
thread.IsBackground = False
thread.Start()
End Sub
這也行不通。我找不到任何建議。我會等待迴應。
感謝
建議:如果您可以簡單地使用ThreadPool(例如'ThreadPool.QueueUserWorkItem(...)';或者使用TPL(即.NET 4中引入的Task),則不應創建自己的線程。創建線程是一項非常昂貴的操作 – stakx 2014-09-19 15:43:36
問題:使用WriteXml寫入文件需要多長時間?您說您每兩秒鐘點擊一次按鈕,但是寫入過程實際上所花的時間比這少很多? – stakx 2014-09-19 15:44:30
我意識到它需要大約10-15毫秒,但是我認爲close()方法不會很快響應。 – user14570 2014-09-19 21:23:24