2014-09-19 25 views
0

我正在使用一個文件。這是代碼:爲什麼不在.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 

這也行不通。我找不到任何建議。我會等待迴應。

感謝

+0

建議:如果您可以簡單地使用ThreadPool(例如'ThreadPool.QueueUserWorkItem(...)';或者使用TPL(即.NET 4中引入的Task),則不應創建自己的線程。創建線程是一項非常昂貴的操作 – stakx 2014-09-19 15:43:36

+0

問題:使用WriteXml寫入文件需要多長時間?您說您每兩秒鐘點擊一次按鈕,但是寫入過程實際上所花的時間比這少很多? – stakx 2014-09-19 15:44:30

+0

我意識到它需要大約10-15毫秒,但是我認爲close()方法不會很快響應。 – user14570 2014-09-19 21:23:24

回答

0

顯然,如果你在兩個線程同時運行的代碼,你得到的併發錯誤作爲第二線程試圖在使用的第一個線程打開文件了。例如,您需要基於文件名進行同步。另一種解決方案是在運行線程時禁用按鈕,並在完成處理後再次啓用該按鈕。

在這個特殊的情況下(大約只有兩秒鐘),你不應該混淆線程。 只需更換以下從您的代碼段與就地方法的調用:

thread = New Threading.Thread(Sub() WriteXml(txtName)) 
thread.IsBackground = False 
thread.Start() 

替換爲:

WriteXml(txtName) 

通過這種方式,在調用中WriteXML會阻止用戶界面線程,直到完成,用戶不會有機會點擊按鈕兩次。

+0

好主意。但是,我無法理解這兩個線程。當我點擊按鈕時,我聽到gui線程運行。 我對嗎 ?如果是這樣,爲什麼兩個線程發生? – user14570 2014-09-19 21:22:00

+0

除了GUI線程外,還會出現額外的線程,因爲您明確地創建它們:New Threading.Thread。第一個出現在您第一次點擊時,第二個出現在您再次點擊時。如果第一個線程還沒有完成,那麼你得到兩個線程。 – 2014-09-22 11:12:34