vb.net

How to run tasks in Parallel?


I have the following code which consists of two methods that I want to run in parallel : LoopA and LoopB

Sub Main(args As String())
    Proceed()
End Sub

Public Async Function Proceed() As Task
    Task.WaitAll(LoopA, LoopB)
End Function

Private Function LoopA() As Task
    While True
        Threading.Thread.Sleep(1000)
        Console.WriteLine("A")
    End While
End Function

Private Function LoopB() As Task
    While True
        Threading.Thread.Sleep(1000)
        Console.WriteLine("B")
    End While
End Function

When running this code, the two tasks don't run in parallel. I'm getting only A, A, A...

enter image description here

Why are these tasks not running in parallel?


Solution

  • Your methods aren't asynchronous.

    Sub Main(args As String())
        Proceed()
    End Sub
    
    Public Function Proceed() As Task
        Task.WaitAll(LoopA, LoopB)
    End Function
    
    Private Async Function LoopA() As Task
        Await Task.Run(Async Function()
                           While True
                               Await Task.Delay(1000)
                               Console.WriteLine("A")
                           End While
                       End Function)
    End Function
    
    Private Async Function LoopB() As Task
        Await Task.Run(Async Function()
                           While True
                               Await Task.Delay(1000)
                               Console.WriteLine("B")
                           End While
                       End Function)
    End Function
    

    If you're not going to actually write those methods so that they are asynchronous then they should each be a Sub rather than a function and you can add the asynchronicity when you call them:

    Sub Main(args As String())
        Proceed()
    End Sub
    
    Public Function Proceed() As Task
        Dim taskA = Task.Run(AddressOf LoopA)
        Dim taskB = Task.Run(AddressOf LoopB)
    
        Task.WaitAll(taskA, taskB)
    End Function
    
    Private Sub LoopA()
        While True
            Threading.Thread.Sleep(1000)
            Console.WriteLine("A")
        End While
    End Sub
    
    Private Sub LoopB()
        While True
            Threading.Thread.Sleep(1000)
            Console.WriteLine("B")
        End While
    End Sub