I’m trying to thread my functions so the main GUI of my application doesn’t fail to respond while the tasks are running.
At the moment my form1.vb is something like this. I’ve cut it down as to reduce the text, but everything works fine:
Public Class MAIR
Private Sub InstallTheAgent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InstallTheAgent.Click
InstallAgentWorker.RunWorkerAsync()
End Sub
Private Sub InstallAgentWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles InstallAgentWorker.DoWork
'Do some stuff
End Sub
Private Sub InstallAgentWorker_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles InstallAgentWorker.RunWorkerCompleted
' Called when the BackgroundWorker is completed.
MsgBox("Installation of the Agent Complete")
ProgressBar1.Value = 0
End Sub
End Class
From my understanding, when the button “Open” is pressed, it calls the function Install and it should start this off in a separate thread, however this doesn’t work.
This seems to work, but the GUI still locks up, suggesting its not in a separate thread
I recommend using the BackgroundWorker Class to implement this kind of basic threading. You don’t have a lot going on here so the basic implementation should suffice. Here is a snippet of how I would go about doing it. My method is a bit too complex (I have base classes and events wired up to catch a lot of worker events) to list here succinctly, so I’ll abbreviate.
This is all translated from C#, so treat it as psuedo-code. The important piece is the documentation of the BackgroundWorker and its behaviors. There is a lot of terrific functionality in this class that takes the headaches of threads away for simple usages. This class is located in
System.ComponentModelso you’ll need the reference and anImportsstatement.Edit: Something I forgot to mention is that once the worker is fired asynchronously, the only manner of tracking it or communicating with the main application is through the
ProgressChangedandRunWorkerCompletedevents. No global variables or cross-thread items will be available, so you’ll have to use the built-in properties to pass in any values (such as computerName it looks like) that you may need during the run.