VB.NET 4.0 Parallel.ForEach AddressOf Multiple Values?
-
22-02-2021 - |
Question
I am trying change from Delegates to Parallel.ForEach
I see the below works fine.
Imports System.Threading.Tasks
Sub Main()
Dim secs() As Integer = {2, 3, 1}
Parallel.ForEach(secs, AddressOf Method2)
End Sub
Sub Method2(ByVal i As Integer)
Console.WriteLine(i.ToString)
End Sub
But what if my Sub takes more then one variable? Can you show me how I should do the below?
Imports System.Threading.Tasks
Sub Main()
Dim secs() As Integer = {2, 3, 1}
Dim Path as String = "Constant"
Parallel.ForEach(secs, Path, AddressOf Method2)
End Sub
Sub Method2(ByVal i As Integer, path as string )
Console.WriteLine(i.ToString, path)
End Sub
Thank you
Solution
You can do this via a Lambda Expression:
Imports System.Threading.Tasks
Sub Main()
Dim secs() As Integer = {2, 3, 1}
Dim Path as String = "Constant"
Parallel.ForEach(secs, Sub(sec) Method2(sec, Path))
End Sub
Sub Method2(ByVal i As Integer, path as string)
Console.WriteLine(i.ToString(), path)
End Sub
This will allow the compiler to create a closure that gets the value of Path, and pass it directly into your method.
OTHER TIPS
Certainly in C#, I'd use a lambda expression to call Method2
instead:
Parallel.ForEach(secs, i => Method2(i, path));
Whether the equivalent will look elegant in VB is beyond the amount of good judgement I have about a language I don't use at 12.50am, but you don't have a lot of other choices really - assuming you don't want to create an instance of another class, passing path
into the constructor, and then using a single-parameter method in that class...
(Oh, and another option would be to change Method2
into a single parameter method where the parameter encapsulated both values. So I guess you do have a few options - but in C# at least, the lambda expression one would be the way to go.)