替换thread.start()和thread.abort()

时间:2018-07-12 14:31:32

标签: vb.net

我需要显示一段时间的表单-基本上是带有进度条的“请稍候,正在加载”表单。当某些操作完成时,我希望此窗口消失。这是我的尝试:

 If IsNothing(mlLabels) Or mblnIsLoading Then Exit Sub
        If mstrPrinterA.Equals(Me.cmbPrinters.Text, StringComparison.OrdinalIgnoreCase) Then
            Exit Sub
        End If
        Dim th As New Threading.Thread(AddressOf WaitPrinter)
        th.Start()
        If mlLabels.IsPrinterOnLine(Me.cmbPrinters.Text) Then
            Me.cmbPrinters.BackColor = Drawing.Color.Green
        Else
            Me.cmbPrinters.BackColor = Drawing.Color.Red
        End If
        th.Abort()
        Do While th.IsAlive

        Loop
        th = Nothing
        mstrPrinterA = Me.cmbPrinters.Text

Private Sub WaitPrinter()
        Dim fw As New FormWaiting
        fw.ShowDialog()
        fw = Nothing
End Sub

但是,我随后读到,使用Thread.Start()Thread.Abort()被认为不是一个好习惯。我还有其他方法可以做到吗?

1 个答案:

答案 0 :(得分:1)

这是我在上面的评论中描述的简单示例。用两种形式创建一个WinForms项目,向Button添加Form1,向BackgroundWorker添加Form2。将此代码添加到Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Display a dialogue while the specified method is executed on a secondary thread.
    Dim dialogue As New Form2(New Action(Of Integer)(AddressOf Pause), New Object() {5})

    dialogue.ShowDialog()

    MessageBox.Show("Work complete!")
End Sub

Private Sub Pause(period As Integer)
    'Pause for the specified number of seconds.
    Threading.Thread.Sleep(period * 1000)
End Sub

,并将此代码发送到Form2

Private ReadOnly method As [Delegate]
Private ReadOnly args As Object()

Public Sub New(method As [Delegate], args As Object())
    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    Me.method = method
    Me.args = args
End Sub

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker1_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    'Execute the specified method with the specified arguments.
    method.DynamicInvoke(args)
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    'Close the dialogue when the work is complete.
    Close()
End Sub

运行项目,然后在启动表单上单击Button。您将看到在执行工作时显示的对话框,然后在完成时消失。对话的编写方式使其可以用来调用带有任何参数的任何方法。调用者可以定义要执行的工作。

在这种情况下,“工作”是一种简单的睡眠,但是您可以在其中放置任何喜欢的东西。请注意,它是在辅助线程上执行的,因此不允许与UI进行直接交互。如果您需要UI交互,那么可以实现,但是需要稍微复杂一些的代码。请注意,即使这样的代码也不允许从执行的方法中返回结果,但是您也可以很容易地支持它。