22-06-19, 03:56 PM
(22-06-19, 03:02 PM)e-coder كتب :سلام عليكمبعد الصلاة على سيدنا محمد
اريد كود لإيقافbackgroundworker
(لست مبرمج VB.NET)
لإيقافه قبل الانتهاء من مهمته عليك بتفعيل الخاصية WorkerSupportsCancellation الخاصة بأدة BackgroundWorker.
وفي زر الإيقاف نفذ الأمر CancelAsync الخاصة بأدة BackgroundWorker.
وفي حدث DoWork الخاصة بأدة BackgroundWorker،
وتحديدًا داخل الحلقة التكرارية افحص CancellationPending الخاصة بأدة BackgroundWorker للتأكد من طلب الإلغاء من أجل الخروج.
تعديل مع ترتيب الكود
كود :
Imports System.ComponentModel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
BackgroundWorker1.WorkerSupportsCancellation = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not BackgroundWorker1.IsBusy Then BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim i As Byte
Do While ListBox1.Items.Count > 0
TextBox1.Text = ListBox1.Items(0)
ListBox1.Items.RemoveAt(0)
If i = 10 Then Threading.Thread.Sleep(6000) : i = 0
i += 1
If BackgroundWorker1.CancellationPending Then Return
Threading.Thread.Sleep(100)
Loop
TextBox1.Clear()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
BackgroundWorker1.CancelAsync()
End Sub
End Class