Ecco un esempio ridotto di come eseguire il lavoro asincrono con VB.Net 4.0.
Immaginiamo di avere un modulo con le seguenti importazioni,
Imports System.Windows.Forms
Imports System.Threading
Imports System.Threading.Tasks
Quel modulo ha due controlli
Private WithEvents DoSomthing As Button
Private WithEvents Progress As ProgressBar
Da qualche parte nella tua applicazione abbiamo una Function chiamato ExecuteSlowStuff , questa funzione è l'equivalente del tuo executeMyQuery . La parte importante è l'Action parametro che la funzione usa per mostrare che sta procedendo.
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
Diciamo che questo lavoro è iniziato con il clic del DoSomething Button .
Private Sub Start() Handled DoSomething.Click
Dim slowStuff = Task(Of Integer).Factory.StartNew(
Function() ExceuteSlowStuff(AddressOf Me.ShowProgress))
End Sub
Probabilmente ti starai chiedendo dove ShowProgress viene da, questa è la parte più disordinata.
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
Nota che perché ShowProgress può essere invocato da un altro thread, controlla le chiamate incrociate. In tal caso si richiama sul thread principale.