0

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!

N.T.C
  • 658
  • 2
  • 9
  • 20

1 Answers1

1

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)
Chief Wiggum
  • 2,784
  • 2
  • 31
  • 44
  • is the Parallel.ForEach available for NET 3.5? – N.T.C Nov 02 '14 at 11:36
  • No, you didn't mention .net 3.5. – Chief Wiggum Nov 02 '14 at 11:37
  • thanks James - the code was written in NET3.5 so I may need to find a way around. – N.T.C Nov 02 '14 at 11:41
  • Is there a good reason sticking to 3.5, lots a good stuff came with v4 and 4.5. If you can upgrade, I'll highly suggest you do. – Chief Wiggum Nov 02 '14 at 11:45
  • 1
    that's the same question I've asked my boss so many times..I don't still get why the company still wants to stick with 3.5. By the way, I've just tried the Parallel.ForEach you suggested, the parallel code took 905ms, while the normal for loop took 3250ms - big improvement! – N.T.C Nov 02 '14 at 11:49
  • Hi Jame, I am wondering after I have make the code run in parallel for each item : item.DoSomethingUseful(), can I further make the task within each item (i.e. the sub DoSomethingUseful() run in parallel as well ? ) – N.T.C Nov 03 '14 at 02:57
  • You want to have a Parallel.ForEach within another Parallel.ForEach? – Chief Wiggum Nov 03 '14 at 04:00
  • Not sure if that really makes sense, but technically it's possible according to this: http://stackoverflow.com/a/12618500/2360972 But this is really getting a bit off topic from the initial question. If you have further question ask a new one and mark this as answered if you're happy with the answer so far. – Chief Wiggum Nov 03 '14 at 04:11