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



我需要显示一个表单一段时间——基本上是一个带有进度条的"请等待,加载"表单。当某个操作完成时,我希望这个窗口消失。这是我的尝试:

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()被认为不是一个好的做法。我还有别的办法吗?

下面是我在上面的评论中描述的一个简单示例。创建一个包含两个表单的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交互,那么这是可以实现的,但您需要稍微复杂一点的代码。请注意,代码本身也不允许从执行的方法返回结果,但您也可以很容易地支持它。

最新更新