1: Public Class Form1
2:
3: Private worker As BackgroundWorkerWithPause = Nothing
4: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonStart.Click
5: worker = New BackgroundWorkerWithPause
6: worker.WorkerReportsProgress = True
7: worker.WorkerSupportsCancellation = True
8: AddHandler worker.ProgressChanged, AddressOf Avanzamento
9: AddHandler worker.DoWork, AddressOf Esecuzione
10: AddHandler worker.RunWorkerCompleted, AddressOf Completamento
11: worker.RunWorkerAsync()
12: End Sub
13:
14: Private Sub ButtonPause_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPausa.Click
15: ' Mette il worker in pausa
16: worker.IsInPause = True
17: End Sub
18:
19: Private Sub ButtonResume_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonResume.Click
20: ' Riavvia il worker
21: worker.IsInPause = False
22: End Sub
23:
24: Sub Esecuzione(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
25: ' Recupera il worker
26: Dim worker As BackgroundWorkerWithPause = CType(sender, BackgroundWorkerWithPause)
27: ' Esegue un conteggio
28: For i As Integer = 1 To 100
29: ' Si ferma per un secondo
30: System.Threading.Thread.Sleep(1000)
31: ' Lancia un progresschanged
32: worker.ReportProgress(i)
33: ' Verifica se è in pausa
34: Do While worker.IsInPause
35: ' Si ferma per un secondo
36: System.Threading.Thread.Sleep(1000)
37: ' Lancia un progresschanged con indicazione della pausa in corso
38: worker.ReportProgress(i, "in pausa")
39: Loop
40: Next
41: e.Result = "Worker completato"
42: End Sub
43:
44: Sub Avanzamento(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs)
45: Me.Label1.Text = e.ProgressPercentage.ToString & "% "
46: If Not e.UserState Is Nothing Then
47: Me.Label1.Text &= e.UserState.ToString
48: End If
49: End Sub
50:
51: Sub Completamento(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
52: Me.Label1.Text = "Terminato"
53: End Sub
54:
55: End Class