Here is a cut down example of how to do Asychrounous Work with VB.Net 4.0.
Lets imagine you have a form that has the following imports,
Imports System.Windows.Forms
Imports System.Threading
Imports System.Threading.Tasks
That form has two controls
Private WithEvents DoSomthing As Button
Private WithEvents Progress As ProgressBar
Somewhere in your application we have a Function
called ExecuteSlowStuff
, this function is the equivalent of your executeMyQuery
. The important part is the Action
parameter which the function uses to show it is making progress.
Private Shared Function ExecuteSlowStuff(ByVal progress As Action) As Integer
Dim result = 0
For i = 0 To 10000
result += i
Thread.Sleep(500)
progress()
Next
Return result
End Function
Lets say this work is started by the click of the DoSomething
Button
.
Private Sub Start() Handled DoSomething.Click
Dim slowStuff = Task(Of Integer).Factory.StartNew(
Function() ExceuteSlowStuff(AddressOf Me.ShowProgress))
End Sub
You're probably wondering where ShowProgress
comes from, that is the messier bit.
Private Sub ShowProgress()
If Me.Progress.InvokeRequired Then
Dim cross As new Action(AddressOf Me.ShowProgress)
Me.Invoke(cross)
Else
If Me.Progress.Value = Me.Progress.Maximum Then
Me.Progress.Value = Me.Progress.Minimum
Else
Me.Progress.Increment(1)
End If
Me.Progress.Refresh()
End if
End Sub
Note that because ShowProgress
can be invoked from another thread, it checks for cross thread calls. In that case it invokes itself on the main thread.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…