2010年7月5日 星期一

BackgroundWorker 背景執行

在很多地方和機制上,必須使用到背景方式去運作;底下為基本架構,就看大家運用發揮了!!


code:
------------------------
Imports System.Threading

Public Class Form1
Dim i As Integer

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

For j As Integer = 1 To 100
i = j
BackgroundWorker1.ReportProgress(i)
Thread.Sleep(500)
If BackgroundWorker1.CancellationPending Then
Return
End If
Next
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If BackgroundWorker1.IsBusy = False Then
i = 0
BackgroundWorker1.RunWorkerAsync()
End If
End Sub

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Label1.Text = i.ToString + "%"
ProgressBar1.Value = i
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Label1.Text = i.ToString + "%"
ProgressBar1.Value = i
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
BackgroundWorker1.CancelAsync()
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ProgressBar1.Value = 0
ProgressBar1.Maximum = 100
End Sub
End Class

沒有留言:

張貼留言