2016-07-26 82 views
0

我有一個winform,做在一個DataGridView文件搜索並顯示結果。我也有顯示文件的圖片框。過程:輸入文件名並單擊搜索,在圖片框中顯示網格和圖片的結果。防止兩次運行子例程以提高性能?

我希望能夠再次點擊搜索,但如果是同一個文件這個時候,我不想跑,因此我的照片過程中產生更好的性能。不知道如何實現這一目標?

+1

我們怎麼能告訴你如何修復/優化代碼時,有沒有代碼? – Plutonix

回答

3

你可以使用一個靜態變量,並設置/查看每個方法被調用一次:

Public Sub SearchForFile(filename As String) 
    Static lastFile As String = Nothing 
    Try 
     'don't run again if the same file is searched for 
     If lastFile = filename Then Return 

     'do your file searching here 
    Finally 
     'always set the last filename to the one we just searched for 
     lastFile = filename 
    End Try 
End Sub 
+0

它再次搜索相同的文件後掛起,不結束結束嘗試循環。 –

+0

在我發佈的代碼中沒有循環,所以我猜你的代碼中沒有'return'。 –

+0

你是什麼意思掛了?它只能掛在一個循環中,所以不能掛在簡單的代碼行上。 –