Running a subroutine in a different thread
When my program starts up I am calling a subroutine in the form load event that copys some files from one network location to another. This process can take from a few seconds to approximately 8-10 seconds. This of course delays any interaction with the form until the copy process is complete. What's the easiest way to run this copy operation in another thread or task so that the form is responsive while the copy operation takes place in the background? Thanks...
Re: Running a subroutine in a different thread
Do you want any sort of visual indicator showing that the operation is taking place?
If so, then use a BackgroundWorker. Specifically, JMcIlhinney has a good CodeBank submission here: https://www.vbforums.com/showthread....ckgroundWorker
Re: Running a subroutine in a different thread
There are several options. You could use the IFileOperation interface to copy the files or folders. You can also use IFileOperation in silent mode if you don't want to see the progress of the copy operation. Alternatively, you can run your subroutine via an Async/Await statement.
Code:
Public Class Form1
Private Async Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ProgressHandler As New Progress(Of Integer)(Sub(value)
Label1.Text = "Files copied: " & $"{value}"
End Sub)
Dim Success As Boolean = Await CopyMyFilesAsync(ProgressHandler)
If Success Then
Else
End If
End Sub
Private Async Function CopyMyFilesAsync(progress As IProgress(Of Integer)) As Task(Of Boolean)
Return Await Task.Run(Async Function()
' Here's where the code goes that copies your files.
' A simple example of a For/Next loop with Task.Delay
' and the ability to display progress.
For i = 0 To 1000
progress?.Report(i)
Await Task.Delay(10)
Next
Return True
End Function)
End Function
End Class
Re: Running a subroutine in a different thread
On a form, I would favor the Backgroundworker, largely because it is more of a UI component. If not on a form, then I would favor the Task approach that Franky showed.
I don't know that there is any particular advantage to one over the other, though.