BackgroundWorker Control
ตัวอย่างนี้ เป็นคอนโทรลที่ใช้ในการทำงานแบบอยู่เบื้องหลัง ไม่กระทบกับการทำงานเบื้องหน้า หรือที่เรียกกันว่า Asynchronous นั่นเองครับ
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For i As Integer = 0 To 100 Step +1
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
Exit For
Else
BackgroundWorker1.ReportProgress(i)
System.Threading.Thread.Sleep(100)
End If
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProcessBar.Value = e.ProgressPercentage
lbl_percent.Text = e.ProgressPercentage & "%"
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled Then
MsgBox("Cancelled")
ElseIf e.Error IsNot Nothing Then
MessageBox.Show(e.Error.Message)
Else
MsgBox("Completed")
End If
BackgroundWorker1.Dispose()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
ProcessBar.Maximum = 100
End Sub
Private Sub btn_Cancel_Click(sender As Object, e As EventArgs) Handles btn_Cancel.Click
BackgroundWorker1.CancelAsync()
End Sub
Private Sub btn_Progress_Click(sender As Object, e As EventArgs) Handles btn_Progress.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Comments
Post a Comment