Search code examples
arraysvb.netperformanceparallel-processingparallels

How to make this code parallel ?


I have written some codes in Vb.Net but it runs quite slow. How can I make it become parallel programming. I need to create 1000 objects of the same type. After initialization, each object will do the same task and the objects are not inter-related to each other.

Dim List as new List(of myObjectClass)

For i as integer = 1 to 1000
  Dim anObject as new myObjectClass()
  anObject.DoSomethingUseful()
  List.add(anObject)
Next

Any idea would be really appreciated!


Solution

  • You could use Parallel.ForEach. Create your 1000 items first and then run the expensive method in a parallel execution

    Dim List as new List(of myObjectClass)
    
    For i as integer = 1 to 1000
      Dim anObject as new myObjectClass()
      List.add(anObject)
    Next
    
    System.Threading.Tasks.Parallel.ForEach(List, Sub(item)
                                            item.DoSomethingUseful()
                                            End Sub)