วันอาทิตย์ที่ 13 มกราคม พ.ศ. 2551

BackGround Worker - Progress Bar

การใช้ Background Worker ก็ลากมาแปะในฟอร์ม แล้วดูว่า เราต้องการทำอะไรบ้างดูใน Property & Event
workerReport Progress = True << รายงานการเปลี่ยนแปลง ใช้คู่กับ Event Progress changed ( มั้งนะ เดาเอา )
workerSupport Cancellation =True << กด Cancel ขณะ Runtime
Event
DoWork ต้องใช้ฟตลอด
RunworkerCompleted ให้ทำอะไรหลังที่ Bgw ทำงานเสร็จ

Private Sub btnGentoDb_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGentoDb.Click

Me.bgw.RunWorkerAsync(.dgv.Rows.Count - 1) '---- ส่งจำนวนรอบ หรือไม่ส่งก็ว่างไว้

End Sub

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

Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

'เรียก แบบ Function ให้เอา ผลลัพธ์ ใส่ให้ e.result ด้วย

' e.Result = Function(parameter)

'เรียกแบบ Sub

Me.AppendData(e.Argument, worker, e) <<<<<< ไปเรียก Method ที่ทำการประมวลผลเช่นดึงค่ามาจาก Db

End Sub

Private Sub bgw_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged

'ทำงานหลัง จากมีการเรียก wk.ReportProgress(Pvalue)

'แสดงผล ความก้าวหน้าการทำงาน

pgb.Value = e.ProgressPercentage

End Sub

Private Sub bgw_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted

If Not (e.Error Is Nothing) Then

'ทำงานเมื่อเกิด exception ทำให้ การทำงานหยุด

MessageBox.Show(e.Error.Message.ToString, " Error ", MessageBoxButtons.OK, MessageBoxIcon.Error)

ElseIf e.Cancelled Then

' ทำงานหลัง เรียก CancelAsync.

MessageBox.Show(" Cancelled")

Else

'กรณี ปกติ ทำงานเสร็จหมดแล้ว มาจบที่ตรงนี้

'ให้กำหนดว่า(เมื่อทำงานเสร็จแล้วให้ทำอะไร)

' Finally, handle the case where the operation succeeded.

'ก็แค่บอกว่า ทำเสร็จ

Me.btnGentoDb.Enabled = True

End If

End Sub

Special Thanks ..

Gf Board Gf Minilab V.1

ไม่มีความคิดเห็น: