What I am trying to do is, creating an application which executes some action. there should be maximum of 10 threads running.
I have the following code, which works fine. I need to send a parameter to “Somework” procedure. How can I do that?
Module Module1
Sub Main()
Dim Task As New Action(AddressOf SomeWork)
dim I as integer
for i=1 to 20
If RunningThread < 10 Then
Task.BeginInvoke(AddressOf Callback, Nothing)
Threading.Interlocked.Increment(RunningThread)
Else
SyncLock (Lock)
tasks.Enqueue(Task)
End SyncLock
End If
next
Console.ReadLine()
End Sub
Private tasks As New Queue(Of action)
Private RunningThread As Integer
Private Lock As New Object
Dim I As Integer = 0
Private Sub SomeWork()
I += 1
Console.WriteLine(I & " doing some work - begin :: " & Now.ToString)
Threading.Thread.Sleep(10000)
Console.WriteLine(I & " doing some work - end :: " & Now.ToString)
End Sub
Private Sub Callback(ByVal o As Object)
If tasks.Count > 0 Then
Dim Task As Action
SyncLock (Lock)
Task = tasks.Dequeue
End SyncLock
Task.BeginInvoke(AddressOf Callback, Nothing)
Else
Threading.Interlocked.Decrement(RunningThread)
End If
End Sub
End Module
Kindly help.
Thanks
You can achieve your requirements easily using the Task Parallel Library (TPL) using Parallel.ForEach. Use a constructor that allows you to specify a ParallelOptions parameter and set the MaxDegreeOfParallelism to your thread limit.