2014-12-19 70 views
1

我正在閱讀肥皂呼叫DataTable需要很長時間才能完成。爲了讓GUI保持活動狀態並更新選取框進度條,我可以在後臺工作人員上執行soapcall並等待它在Runworkercompleted子文件中設置全局變量標誌。 該表填充得當,並且dowork返回,但完成的runworker永遠不會被調用。vb.net Backgroundworker DoWork沒有結束

如果我重新編寫這個設置標誌爲DoWork的最後一件事,然後下一次我打電話TableGetterThread.RunWorkerAsync它告訴我,它不能運行的任務,同時 (附加信息:這BackgroundWorker當前正忙,不能同時運行多個任務。 )

任何幫助我做錯了很多讚賞。

waiting = True 
    TableGetterThread.RunWorkerAsync(New tableInfo(tablename, filter)) 
    While waiting 
     Me.Refresh() 
     Threading.Thread.Sleep(100) 
    End While 

Private Sub TableGetterThread_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles TableGetterThread.DoWork 
    Dim user As String = "username" 
    Dim pass As String = "password" 
    getTable_Table = Nothing 
    getTable_Table = bromcomReader.getEntityData(e.Argument.tablename, e.Argument.Filter, user, pass).Tables(0) 
    getTable_Table.TableName = e.Argument.tablename 
    Console.WriteLine("FinishedDoWork") 
End Sub 

Private Sub TableGetterThread_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles TableGetterThread.RunWorkerCompleted 
    Console.WriteLine("Completed") 
    waiting = False 
End Sub 
+0

從DoWork代碼中刪除'Console.WriteLine(「FinishedDoWork」)''。 – 2014-12-19 10:21:46

+0

相同的效果,只是稍後添加,以確保代碼不掛在bromcomReader.getEntityData() – Peterp 2014-12-19 10:26:24

+0

認爲你的while循環是問題。那之後會發生什麼?你不能在RunWorkerCOmpleted Sub的wihle循環之後調用這些東西嗎? – 2014-12-19 12:18:47

回答

1

這個缺陷是在邏輯本身。主線程和RunWorkerCompleted必須在同一個線程上運行。所以,當你在等待Waiting被設置爲false時,你在主線程中,所以RunWorkerCompleted永遠不會被調用。將waiting = False設置爲BackgroundWorker_Dowork的最後一步。我建議你使用AutoReset Event而不是While loop等待。

您可以使用此代碼作爲參考。

Public Class Form1 

    Private Property waiting As Boolean 

    Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
     Console.WriteLine("Hey") 
     waiting = False 
    End Sub 

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted 

    End Sub 

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 
     waiting = True 
     BackgroundWorker1.RunWorkerAsync() 
     While waiting 
      Me.Refresh() 
      Threading.Thread.Sleep(100) 
     End While 
    End Sub 
End Class