Visual Basic:我如何将我的工作放在 backgroundworker 中

Visual Basic: How I Can put my work at backgroundworker

我正在尝试每隔 x 秒截屏一次,然后 运行 在 backgroundworker 上截屏 但我无法阻止它。 这是我的 class 表格:

Imports System.IO
Imports System.Drawing.Imaging
Imports System.Threading
Imports System.ComponentModel

Public Class Form1
Dim rdm As New Random()
Dim ButtonOneClick As Boolean 'Make sure this is before all subs
Private bw As BackgroundWorker = New BackgroundWorker

Public Sub New()
    InitializeComponent()

    bw.WorkerReportsProgress = True
    bw.WorkerSupportsCancellation = True
    AddHandler bw.DoWork, AddressOf bw_DoWork

End Sub
'run and save screen-shoot'
Sub GetData()
 'My code to save screen shot'
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    If Not bw.IsBusy = True Then
        bw.WorkerSupportsCancellation = True
        bw.RunWorkerAsync()
    End If
    If bw.CancellationPending Then
        bw.CancelAsync()
    End If


End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'cancel
    If bw.IsBusy AndAlso bw.WorkerSupportsCancellation Then
        bw.CancelAsync()
        Button2.Enabled = False
    End If
End Sub


Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
    Dim myThread As New System.Threading.Thread(AddressOf GetData)
    bw.WorkerSupportsCancellation = True
    For x As Integer = 1 To 15
        If bw.CancellationPending Then
            e.Cancel = True
            Exit For
        End If

        ' Perform a time consuming operation and report progress.
        myThread.Start()
        bw.ReportProgress(3000)

    Next
End Sub

Private Sub bw_Down()
    Throw New NotImplementedException
End Sub

End Class

我一直在寻找解决方案,但没有奏效。 我是 Visual basic 的新手。所以;希望你忽略我的错误 请帮忙

您应该选择使用 Thread 或 BackgroundWorker,而不是两者都使用。
因为 BackgroundWorker 本身就是一个 Thread,所以它不会使您的表单冻结。
更改 bw_DoWork 至:

Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    For x As Integer = 1 To 15
        If sender.CancellationPending Then
            e.Cancel = True
            Exit For
        End If
        GetData()  'Screenshot
        Thread.Sleep(1000)  'The delay between screenshots (ex: 1000 means 1sec)
        bw.ReportProgress(x)  'Report Progress (1 to 15)
    Next
End Sub