|
ปกติผมไม่ได้ใช้หรอกครับ เพราะการโหลดข้อมูลมันค่อนข้างจะเร็วอยู่แล้ว แต่ไม่เป็นไร ก็เลยเขียนโค้ดแสดงการเปรียบเทียบระหว่างการใช้ กับไม่ใช้ Background Worker มาให้ได้ดูกัน ...
แบบแสดงผลธรรมดา
แบบใช้ Background Worker
ใช้ Control ...
- BackgroundWorker1 (อยู่ในกลุ่มเครื่องมือ Toolbox)
- TextBox1
- Button1 และ Button2
- ProgressBar1
- lblProgress (แสดงจำนวน %)
โค้ดโปรแกรม ...
- Public Class frmBackgroundWorker
- Private Sub frmBackgroundWorker_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
- TextBox1.Text = 100
- TextBox1.MaxLength = 3
- '// Initialized
- With BackgroundWorker1
- .WorkerReportsProgress = True
- .WorkerSupportsCancellation = True
- End With
- '//
- Control.CheckForIllegalCrossThreadCalls = False
- End Sub
- '// Background Worker Process
- Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
- If Trim(TextBox1.Text) = "" Then Return
- '//
- BackgroundWorker1.RunWorkerAsync()
- End Sub
- '// BackgroundWorker - Events DoWork
- Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
- For i = 1 To 100
- TextBox1.Text = i
- BackgroundWorker1.ReportProgress(i)
- Threading.Thread.Sleep(100)
- lblProgress.Text = ProgressBar1.Value & "%"
- Next
- End Sub
- '// When change occurs.
- Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
- Me.ProgressBar1.Value = e.ProgressPercentage
- End Sub
- '// When finished.
- Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
- MessageBox.Show("Done Complete.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
- End Sub
- '// Normal Process
- Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
- If Trim(TextBox1.Text) = "" Then Return
- '//
- Dim Max As Integer = 100
- For i = 1 To Max
- TextBox1.Text = i
- lblProgress.Text = i.ToString & "%"
- ProgressBar1.Value = (100 / Max) * i
- Threading.Thread.Sleep(100)
- Next
- End Sub
- ' / --------------------------------------------------------------------------
- ' / Get numeric only.
- Function CheckDigitOnly(ByVal index As Integer) As Boolean
- Select Case index
- Case 48 To 57 ' 0 - 9
- CheckDigitOnly = False
- Case 8, 13 ' Backspace = 8, Enter = 13
- CheckDigitOnly = False
- Case Else
- CheckDigitOnly = True
- End Select
- End Function
- Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
- If e.KeyChar = Chr(13) Then
- e.Handled = True
- Call Button1_Click(sender, e)
- Else
- e.Handled = CheckDigitOnly(Asc(e.KeyChar))
- End If
- End Sub
- End Class
คัดลอกไปที่คลิปบอร์ด
|
|