VB.NET multithreading

609 views Asked by At

I need to do a taks on a list of parameters: all those tasks are independant. I don't see how to do it.. I tried to divide the parameters into one "shared class" and make a different instance of a class for each item in the list, and then launch the function on each instance asynchroneously :

Imports System.Runtime.InteropServices
Imports System.IO
Public Class DataContainer
    Public Parameters as double 'obviously simplified code ;-)
End Class
Public Class JobDoer
    Public CommonData As DataContainer
    Public PrivData as double
    Public Async Function YesWeCan() As Task(Of Boolean)
        Return Task.Factory.StartNew(Of Boolean)(
             DoIt(CommonData.Parameters , PrivData)
         )

    End Function
    Public Function DoIt(a as double,b as double)
         return 0
    end function
 End Class

==> Task is not defined...

.NET framework 3.0 VS 2015

Any ideas?

1

There are 1 answers

3
Crusha K. Rool On BEST ANSWER

The Async and Await keywords are not available in .NET 3.0. They have been introduced in .NET 4.5, although you can already make use of them in 4.0 (with some modifications, like having to use TaskEx instead of Task for some of the static functions) if you import the Microsoft.Bcl.Async package via NuGet.

You can of course simply start new threads without having to use Async/Await.

Or you could use the ThreadPool. Here is some code I made back in the past, which was originally written in C#. I converted it now and removed the parts that would require at least .NET 4.0. Didn't test it, though.

Private Sub SubmitWorkToThreadPool()
    For i as Integer = 0 To yourWorkItems.Count 'Adjust this loop so it adds all your tasks to the thread pool.
        'customParameter is passed as parameter 'state' to the DoParallelWork function.
        ThreadPool.QueueUserWorkItem(AddressOf DoParallelWork, customParameter)
    Next
End Sub

Private Sub DoParallelWork(state As Object)
    'TODO: Add code to be executed on the threadpool
End Sub

In the 4.0 version I had it written in a way that would allow me to wait for all work items to be completed after submitting it to the threadpool by using a CountdownEvent. But that class only exists since 4.0, so I removed it. You might have to find another way if you need to wait for everything to be done.