Visual Basic:我如何将我的工作放在后台工作者身上

时间:2015-02-10 11:14:51

标签: vb.net multithreading backgroundworker

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

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的新手。所以;希望你忽略我的错误 请帮忙

1 个答案:

答案 0 :(得分:1)

您应该选择使用线程或BackgroundWorker,而不是两者。
原因BackgroundWorker本身就是一个线程,因此它不会使您的表单冻结。
将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