1

I basically have 3 Subs, I would like them to run together and converge once they finish and continue with the main sub. I can do this in C#, I am having difficulty managing to do this in VB.Net

Basically I am trying to accomplish something like the diagram below.

                   |---sub1()---|
Start sub()--------|---sub2()---|---main()----> end sub()
                   |---sub3()---|

Private Sub Manual_Trades_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim T1 As New Task(AddressOf sub1)
    Dim T2 As New Task(AddressOf sub2)
    Dim T3 As New Task(AddressOf sub3)
    T1.Start()
    T2.Start()
    T3.Start()
    Task.WaitAll(T1, T2, T3)
End Sub 

Sub sub1()
    'Do something that takes time
End Sub

Sub sub2()
    'Do something that takes time
End Sub

Sub sub3()
    'Do something that takes time
End Sub
Adas
  • 404
  • 2
  • 19
  • I think Thread.Sleep doesn't work well with task, you should be using [Task.Delay](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.delay?redirectedfrom=MSDN&view=netframework-4.7.2#overloads). Not 100% sure of that. – the_lotus Feb 01 '19 at 16:33
  • @the_lotus yeah I just got rid of that to clarify the question properly – Adas Feb 01 '19 at 16:34
  • 2
    What would be different from the c# code? – LarsTech Feb 01 '19 at 16:42
  • 2
    What's wrong with the `WaitAll()` you have now? – Joel Coehoorn Feb 01 '19 at 16:45
  • I am not sure, for some reason my code runs faster when I run it Synchronously. So I assumed maybe I did something wrong here, used an improper method thus the code snippet. My code is accessing the SQL server to fetch some data to fill up a datatable tho. – Adas Feb 01 '19 at 16:56
  • 2
    @Adas parallel does not always mean faster. There can be limit when they try to access shared resources or limited by hardware capability. – the_lotus Feb 01 '19 at 17:13

1 Answers1

0

Based on your first sample. You could try using Task.Run instead. Seems like it's the suggested method of doing it.

Sub sub1()
    Threading.Thread.Sleep(1000)
    Console.WriteLine("1")
End Sub

Sub sub2()
    Threading.Thread.Sleep(2000)
    Console.WriteLine("2")
End Sub

Sub sub3()
    Threading.Thread.Sleep(3000)
    Console.WriteLine("3")
End Sub

Sub RunAllAndWait()

    Dim T1 As Task = Task.Run(AddressOf sub1)
    Dim T2 As Task = Task.Run(AddressOf sub2)
    Dim T3 As Task = Task.Run(AddressOf sub3)

    Task.WaitAll({T1, T2, T3})

End Sub
the_lotus
  • 12,668
  • 3
  • 36
  • 53
  • When I do this, it says Run is not a member of Task, when i switch run with start, it says addressOf cannot be converted to taskscheduler because taskscheduler is not a delegate type – Adas Feb 01 '19 at 18:07