公共背景工作者

时间:2017-08-03 06:27:58

标签: vb.net backgroundworker public

因此,使用此解决方案进行后台工作程序实现(https://msdn.microsoft.com/ru-ru/library/cc221403(v=vs.95).aspx),如何实现公开版本?我不希望在我的所有表单中增加这段代码(我有大约4个表单,我想在所有表单中使用后台工作程序)。基本上,我想创建1个类并将此类用作“主”(只需传递控制启动/取消按钮,进度条和子应该在“工作”下工作)。

你能告诉我一个怎样的方法吗?我尝试了很多工作人员,但我不确定是否正确。例如,我应该为此目的使用Public事件和委托吗?

提前谢谢

//我对“主人”背景工作者的建议“。抱歉这是未经测试的代码,我只是把草稿。

Public class BgW 
    'Event for start/cancel button. On each form there is button which raise 
    'this event and then this event raise procedure to
    'start/cancel process (event passes arguments like 
    'sender of the button to distinguish start or cancel 'button)
    Public btnclick Event (sender,e)

    Dim WithEvents as Bgw

    Public Sub New()
    InitializeComponent()
    bw.WorkerReportsProgress = True
    bw.WorkerSupportsCancellation = True
    '??? - will trigered to implement below procedure
    AddHandler ??????, AddressOf bw_DoWork
    AddHandler ?????, AddressOf bw_ProgressChanged
    AddHandler ??????, AddressOf bw_RunWorkerCompleted

End Sub


   Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BgW.btnclick 'this is a triger to run this procedure
    'Depends on sender I will do next controls
    sender(start).Enabled = False
    sender(cancel).Enabled = True

    TestWorker = New System.ComponentModel.BackgroundWorker
    TestWorker.WorkerReportsProgress = True
    TestWorker.WorkerSupportsCancellation = True
    TestWorker.RunWorkerAsync()
End Sub

Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BgW.btnclick 'this triger to stop worker
    TestWorker.CancelAsync()
End Sub

Private Sub TestWorker_DoWork(SomeSub As Sub, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles TestWorker.DoWork
        If TestWorker.CancellationPending Then
            Exit For
        Else
           'implement procedure. I will pass some sub to implement it here.
            SomeSub()
        End If

End Sub
end class

我明白我对背景工作者的理解很差,但这是我的愿景。请帮助我如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

我想,你知道这个网站:https://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

我第一次与背景工作者打交道,我遇到了和你一样的问题。以下是问号的代码:

AddHandler bw.DoWork, AddressOf bw_DoWork
AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted

请记住阅读上面的链接,因为微软的这个方法有一个很好的例子来运行一个后台工作者。

没有问题,如果你希望将它放在一个类中并使类的实例运行BGW。如果是这样,你应该编写一个Public Sub,它启动Private BGW。