我試圖讓我的一個程序變成多線程應用程序,但我已經打了一個對,我在下面的代碼記錄碰壁的。任何幫助,我可以得到這個,使其行爲正常將不勝感激,所以我可以擴展這個存根到我現有的應用程序的更有效的版本。這個多線程VB.NET(2010 Express Edition)程序爲什麼不能正常工作?
謝謝您對此事有任何意見。 - 亞倫
Imports System.Threading
Public Class frmMain
''' <summary>Initializes the multithreaded form</summary>
Private Sub Initialize() Handles MyBase.Load
AddThread(AddressOf Update_UI)
running = True
For Each Thread In ThreadPool
Thread.IsBackground = True
Thread.Start()
Next
End Sub
''' <summary>Terminates the multithreaded form</summary>
Protected Overrides Sub Finalize() Handles MyBase.FormClosing
running = False
For Each Thread In ThreadPool
Thread.Join()
Thread = Nothing
Next
End Sub
''' <summary>Adds a worker thread to the ThreadPool</summary>
''' <param name="pointer">The AddressOf the function to run on a new thread.</param>
Private Sub AddThread(ByRef pointer As System.Threading.ParameterizedThreadStart)
Dim newthread As Integer
If ThreadPool Is Nothing Then newthread = 0 Else newthread = ThreadPool.GetUpperBound(0) + 1
ReDim Preserve ThreadPool(newthread)
ThreadPool(newthread) = New Thread(pointer)
End Sub
''' <summary>Updates the User Interface</summary>
Private Sub Update_UI()
'HELP: The commented out lines in this subroutine make the program work incorrectly when uncommented.
'HELP: It should echo 'output' to the titlebar of frmMain, but it also makes the form unresponsive.
'HELP: When I force the form to quit, the 'termination alert' does not trigger, instead the application hangs completely on Thread.Join (see above).
'HELP: If I remove DoEvents(), the form is unable to be closed...it simply goes unresponsive. Shouldn't the multithreading keep us from needing DoEvents()?
'If Me.InvokeRequired Then
' Me.Invoke(New MethodInvoker(AddressOf Update_UI))
'Else
While running
Dim output As String = System.DateTime.Now + " :: Update_UI() is active!"
Debug.Print(output)
'Application.DoEvents()
'Me.Text = output
End While
Debug.Print(System.DateTime.Now + " :: Termination signal recieved...")
'End If
End Sub
Delegate Sub dlgUpdate_UI()
Private ThreadPool() As Thread
Private running As Boolean
End Class
我嘗試過爲此使用BackgroundWorker,但它似乎有使用線程相同的問題......但增加了不知道如何在此上下文中使用它。 –
但至少通過對此的分析,我可以更好地理解我在做什麼錯了我當前使用的線程......感謝您提供有關使用計時器執行更新分配以及拉取我的kill代碼的提示從Finalize()...中刪除,這不會影響這個特定的程序,但它會在我計劃的更復雜的程序中。 –
你會如何建議處理Finalize例程?我希望它在FormClosing上運行,但不會受到潛在的超時和崩潰(所以我可以在更復雜的表單上使用此模板)。換句話說......有沒有辦法阻止表單閉包等待Finalize完成? –