线程数限制的线程限制并使用参数执行proc

时间:2012-07-11 16:18:16

标签: vb.net multithreading parameters

我要做的是创建一个执行某些操作的应用程序。最多应该有10个线程在运行。

我有以下代码,工作正常。我需要向“Somework”程序发送一个参数。我怎么能这样做?

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

请帮助。

由于

1 个答案:

答案 0 :(得分:2)

您可以使用Task Parallel Library(TPL)使用Parallel.ForEach轻松实现您的要求。使用允许您指定ParallelOptions参数并将MaxDegreeOfParallelism设置为线程限制的构造函数。