Don't do things like this:
ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback( _
AddressOf Task), arg)
thread.WaitOne()
To spawn a new thread and then immediately wait for that thread to finish on the thread that started it is the same as not threading it at all. You might as well do all of the work in
Task
in the button click event.
You want the thread to do it's work and then notify back to the thread that started it (possibly with status updates being notified back as the work is being done).
What you're doing in your application is a
WaitOne
on the UI thread, if you do that your UI will lock until the event is notified, this is bad.
If you're just starting out with multithreading your application, look into using the
BackgroundWorker
, that comes with events that you can hook into to do things like status updates and report when task is completed.
Something like this might work for you:
Imports System.Threading
Imports System.ComponentModel
Public Class Form1
Private Sub startButton_Click(sender As System.Object, e As System.EventArgs) Handles startButton.Click
Dim worker As New BackgroundWorker()
worker.WorkerSupportsCancellation = True
worker.WorkerReportsProgress = True
AddHandler worker.DoWork, AddressOf MyLongRunningOperation
AddHandler worker.ProgressChanged, AddressOf MyProgressUpdate
AddHandler worker.RunWorkerCompleted, AddressOf MyWorkHereIsDone
worker.RunWorkerAsync()
End Sub
Sub MyLongRunningOperation(sender As Object, e As DoWorkEventArgs)
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
For i = 0 To 10
If worker.CancellationPending Then
e.Cancel = True
Exit For
End If
' Do your work
Thread.Sleep(1000)
worker.ReportProgress(i * 10)
Next
End Sub
Private Sub MyProgressUpdate(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
progressBar.Value = e.ProgressPercentage
statusText.Text = e.ProgressPercentage & "% complete"
End Sub
Private Sub MyWorkHereIsDone(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
If e.Cancelled = True Then
completedText.Text = "Operation was cancelled!"
ElseIf e.Error IsNot Nothing Then
completedText.Text = "Operation failed: " & e.Error.Message
Else
completedText.Text = "I am all done!"
End If
End Sub
End Class
It relies on
progressBar
,
statusText
and
completedText
being on your form. I haven't wired up a cancel button but that should be self explanatory I think.
Hope this helps,
Fredrik