Houlahan Houlahan - 1 year ago 103
Vb.net Question

Wait for threads to finish before carrying on

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))

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.

Answer Source

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]())


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download