0

I have a number of threads that need running (about 160) creating files and then copying them to various places:

'Files is basically a list of strings
'which is passed to a function that creates a file from a number of database fields
'when thats done it copies it to a number of places

       For Each x In Files
            Dim Evaluator = New Thread(Sub() API.Files.Create.Standard(x))
            Evaluator.Start()
        Next

What i want it to do is fire off the 160 or so threads (with permitter x) then wait for all the threads to finish and then continue with the rest of the program.

Houlahan
  • 783
  • 3
  • 19
  • 46

1 Answers1

6

If you are using Framework 4.0 (For 3.5 Jon Skeet has solution @ Can I use the task parallel library in a .Net 3.5 project? ) . Rather than using Thread you can use TPL (Task Processing Library). It is wrapper around Threads. So in nutshell, Create Tasks and it has static method Task.WailAll which allows intended functionality.

Dim tasks = New Task(160) {}
For i As var = 0 To 160
    Dim x = i
    tasks(i) = Task.Factory.StartNew(Function() New CreateFileClass(x).[Do]())
Next

Task.WaitAll(tasks)

I have used code from Task Parallel Library - Know when all tasks are finished and using online C# to VB.Net converter produced above code. I hope it helps.

Community
  • 1
  • 1
TorontoKid
  • 733
  • 1
  • 7
  • 15
  • `Dim x = i` is redundant, otherwise a good answer. I was going to post mine with a similar solution, but you made it earlier. +1 – Victor Zakharov May 01 '13 at 17:27
  • I agree it is redundant. Evil copy/paste :). – TorontoKid May 01 '13 at 17:29
  • 1
    If going the TPL route, the case for the OP might even be made simpler with a straight `Parallel.ForEach(Files, Sub(x) API.Files.Create.Standard(x))`. – J... May 01 '13 at 17:35