How to put this function inside a separate thread

旧街凉风 提交于 2019-12-06 07:37:41

There is a Windows Forms component called BackgroundWorker that is designed specifically to offload long-running tasks from the UI thread to a background thread, leaving your form nice and responsive.

The BackgroundWorker component has an event called DoWork that is used to execute code on a separate thread. Drag the BackgroundWorker component onto your form and then do something like this:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles start_button.Click
    NameOfDirectory = userSelectedFolderPath
    backgroundWorker1.RunWorkerAsync(NameOfDirectory)
End Sub

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Dim directoryName as string = e.Argument

    MediaInfo(directoryName)
End Sub

A couple of links that might be useful are the MSDN BackgroundWorker page and an example on Code Project.

HTH

igrimpe

There are around 5 dozen ways to solve the problem. I will show just 3 of them:

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    ' fire and forget:
    Task.Run(Sub() FooA()).ContinueWith(Sub() FooB()).ContinueWith(Sub() FooC())
    Console.WriteLine("Button1 done")

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    ' fire and forget:
    Task.Run(Sub()
                 FooA()
                 FooB()
                 FooC()
             End Sub)
    Console.WriteLine("Button2 done")

End Sub

Private Async Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    ' wait but dont block:
    Await Task.Run(Sub()
                       FooA()
                       FooB()
                       FooC()
                   End Sub)
    Console.WriteLine("Button3 done")

End Sub

Private Sub FooA()
    Threading.Thread.Sleep(1000)
    Console.WriteLine("A")
End Sub

Private Sub FooB()
    Threading.Thread.Sleep(1000)
    Console.WriteLine("B")
End Sub

Private Sub FooC()
    Threading.Thread.Sleep(1000)
    Console.WriteLine("C")
End Sub

End Class

I would suggest the one with Await (IF FW 4.x and VS2012 is not an issue).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!