等待多个BackgroundWorkers完成

时间:2018-01-31 13:41:55

标签: vb.net multithreading multidimensional-array backgroundworker

我必须使用多个大的二维数组(例如1024 x 128),在我的代码的一部分中,我需要转置一些(最多12个)。 该过程需要相当长的时间,我试图尽可能加快速度。知道VB.NET支持多线程我在这里和那里读了不同的源,并且可以在主子例程中提出以下代码:

RunXTransposingThreads(Arr1, Arr2, Arr3, ...)

使用BackgroundWorker作为我的解决方案的一部分:

Private Sub RunXTransposingThreads(ParamArray ArraysToTranspose() As Array)
    Dim x = CInt(ArraysToTranspose.GetLength(0)) - 1
    Dim i As Integer
    For i = 0 To x
        Dim worker As New System.ComponentModel.BackgroundWorker
        AddHandler worker.DoWork, AddressOf RunOneThread
        AddHandler worker.RunWorkerCompleted, AddressOf HandleThreadCompletion
        worker.RunWorkerAsync(ArraysToTranspose(i))
    Next
End Sub

Private Sub RunOneThread(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
    Dim Transposed(,) As Single = Array.CreateInstance(GetType(Single), 0, 0) ' I need this to be like that in order to use other functions later
    Transposed = Transpose2dArray(CType(e.Argument, Single(,)))
    e.Result = Transposed
End Sub

Private Sub HandleThreadCompletion(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
    Debug.Print("Process complete")
End Sub

Function Transpose2dArray(Of Array)(ByVal inArray As Array(,)) As Array(,)

    Dim x = CInt(inArray.GetLength(1))
    Dim y = CInt(inArray.GetLength(0))
    Dim outArray(x - 1, y - 1) As Array

    For i = 0 To x - 1
        For j = 0 To y - 1
            outArray(i, j) = inArray(j, i)
        Next
    Next

    Transpose2dArray = outArray

End Function

线程似乎有效,因为在执行RunXTransposingThreads之后某些时候,我在屏幕上看到了一些"处理完成"。问题是:如果我还没有转换数组,如何停止执行主代码?

2 个答案:

答案 0 :(得分:2)

正如其他人所说,BackgroundWorker已经过时了。幸运的是,还有许多其他现代方法可以做到这一点。

因此,我不会向您展示使您的代码与BackgroundWorker一起使用的内容。相反,我将通过使用任务,一种现代方式向您展示如何做同样的事情。希望它有所帮助。

Function RunXTransposingTasks(ParamArray ArraysToTranspose() As Array) As Array
    Dim taskList = New List(Of Task(Of Single(,))) ' our tasks returns Arrays

    For Each arr In ArraysToTranspose
        Dim r = arr
        taskList.Add(Task.Run(Function() Transpose2dArray(r)))
    Next

    Task.WhenAll(taskList) ' wait for all tasks to complete. 
    Return taskList.Select(Function(t) t.Result).ToArray()
End Function

Function Transpose2dArray(inArray As Array) As Single(,)
    Dim x = inArray.GetLength(1) - 1
    Dim y = inArray.GetLength(0) - 1
    Dim outArray(x, y) As Single

    For i = 0 To x
        For j = 0 To y
            outArray(i, j) = inArray(j, i)
        Next
    Next

    Return outArray
End Function

' Usage
' Dim result = RunXTransposingTasks(Arr1, Arr2, Arr3, ...)

答案 1 :(得分:-1)

您可以尝试使用build-in function复制数据

Array.Copy(inArray, outArray, CInt(inArray.GetLength(1)) * CInt(inArray.GetLength(0)))

还有一些关于如何使用Parallel.ForEach的great example