当所有线程都完成vb.net时更新ui

时间:2014-03-17 14:26:53

标签: vb.net

我有一个vb.net代码,其中,在按钮单击时,我将禁用另外两个按钮并启动两个线程。一旦这两个线程完成,我应该再次启用这两个按钮。 这是近似的vb.net代码:

button click()
  button2.enable = false
  button3.enable = false

  thread1.start
  thread2.start

//once these two threads completes

 button2.enable = true
 button3.enable = true
end

1 个答案:

答案 0 :(得分:0)

我认为Thread.Join()正是您所寻找的,但它是一个阻塞调用,如果从其主题执行,将冻结您的UI。

button click()
    button2.enable = false
    button3.enable = false
    thread1.start
    thread2.start
    thread1.join
    thread2.join
    button2.enable = true
    button3.enable = true
end

但是,这是一个优秀的解决方案,因为它使用Async...Await来阻止UI线程

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Button2.Enabled = False
    Button3.Enabled = False
    Await executeThreads()
    Button2.Enabled = True
    Button3.Enabled = True
End Sub

Private Function executeThreads() As Task(Of Boolean)
    thread1.Start()
    thread2.Start()
    thread1.Join()
    thread2.Join()
End Function