所以基本上我想我的應用程序運行一個相當cpu密集型的方法,同時它應該不斷地在不同的窗體上顯示狀態信息。爲了防止這種狀態凍結,我認爲將代碼外包給一個新線程是一個好主意。Vb.Net - 調用任務
首先,我嘗試使用基本線程並調用應顯示狀態消息的richtextbox控件。 - 問題是 - 我需要知道線程何時完成以繼續執行主線程。顯然,我不能簡單地在我的主線程中運行一個循環來檢查過程是否完成,因爲這會導致我的GUI凍結。
所以我做了一點研究,並發現了關於任務。 這是它的外觀:
Dim z as new complexProcessClass
Dim taskA = task.Factory.StartNew(Sub() z.start())
taskA.Wait()
If taskA.IsCompleted Then
MsgBox("finished")
End If
每當進程報告狀態我用這個:
Public Class complexProcessClass
dim statusWindow as statusForm
Public Sub start()
statusWindow = new statusForm
'complex code here
reportStatus("bla")
'complex code here
reportStatus("blabla")
'complex code here
End Sub
Private Delegate Sub UpdateTextHandler(ByVal Text As String)
Private Sub reportStatus(Byval s as String)
If z.RichTextBox1.InvokeRequired Then
Try
z.RichTextBox1.Invoke(New UpdateTextHandler(AddressOf xform.RichTextBox1.AppendText), s)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Else
z.RichTextBox1.AppendText(s)
End If
End Sub
,但它只是保持凍結的invoke調用 - 沒有錯誤信息 - 什麼?
任何人都可以告訴我正確的方法來做到這一點? - 和請沒有BackgroundWorker的解決方案;)
在此先感謝