문제

I'm looking to run sequential sub procedures in a background thread. and am wondering if it is permissible to do such by creating a background worker and then calling each procedure separately like so...

Private Sub BGW_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) 
_Handles BGW.DoWork

Procedure1()
Procedure2()
Procedure3()

End Sub

Will this run each procedure in the background thread?

Also, reading other posts some suggested to use a List<svnCommand> and pass them to RunWorkerAsync in C#, while others suggested using Tasksmethod, both of which I have no knowledge of. Will any of these two work and what are they?

도움이 되었습니까?

해결책

No, it is not necessary to put each subroutine in its own BackgroundWorker. I regularly call multiple subroutines from my DoWork handler. Any subroutines called from that handler will execute in the background thread.

다른 팁

Figured it out.

For full completeness and reference, there are two ways to do this. One is by calling the subs from BackgroundWorker DoWork like such:

Public Class Form1
    Dim var1 As Integer = 0
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Run background worker
        BackgroundWorker1.RunWorkerAsync()
    End Sub
    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        'Run task 1
        Task1_Code()
        'Run task 2
        Task2_Code()
        'Show variable
        MessageBox.Show(var1)
    End Sub
    Sub Task1_Code()
        'Wait 10 seconds
        Threading.Thread.Sleep(10000)
        'Sets var1 to 5
        var1 = 5
    End Sub
    Sub Task2_Code()
        'Wait 10 seconds
        Threading.Thread.Sleep(10000)
        'Same as var1= var1*5
        var1 *= 5
    End Sub
End Class

The other is by using the Task class.

Imports System.Threading.Tasks

Public Class Form1
    Dim var1 As Integer = 0
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'Dim the task list and start excecuting
        Dim task1 As task = Task.Factory.StartNew(AddressOf Task1_Code).ContinueWith(AddressOf Task2_Code)
        'Waits for tasks to complete within 90 seconds or less
        task1.Wait(90000)
        'Shows variable
        MessageBox.Show(var1)
    End Sub
    Sub Task1_Code()
        'Wait 10 second
        Threading.Thread.Sleep(10000)
        'Sets var1 to 5
        var1 = 5
    End Sub
    Sub Task2_Code()
        'Wait 10 second
        Threading.Thread.Sleep(10000)
        'Same as var1= var1*5
        var1 *= 5
    End Sub
End Class

For more info on tasks go to the post on sequential tasks using vb.net.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top