按顺序启动的多个线程 vb.net



我有一个方法,我想运行多个线程以更快地完成它。

Public Sub createMaster()
    For intLoop = 0 To _MasterCount - 1 Step _Step
        _MasterCollection(intLoop) = New Champion(_MasterIDCollection(intLoop), _RRM.returnChampionInformation(_MasterIDCollection(intLoop).Substring(0, _MasterIDCollection(intLoop).Length() - 1), "na"))
    Next
End Sub

所以,该方法基本上为我创建了一个集合。我尝试做多个线程来更快地完成它,制作冠军实际上需要一秒钟。有没有办法使intLoop成为特定的变量?我尝试制作intloop = _Start每次_Start增加一,最终_Start各种数字。我的主要内容是:

    Dim thread1 As New System.Threading.Thread(AddressOf createMaster)
    thread1.Start()
    Dim thread2 As New System.Threading.Thread(AddressOf createMaster)
    thread2.Start()
    thread1.Join()
    thread2.Join()

我尝试在线程中使用 For 循环,但它似乎也不起作用。有谁知道如何以任何方式使这项工作?

可以将当前代码转换为使用 LINQ 将_MasterIDCollection映射到Champion实例:

_MasterCollection = (
    From id In _MasterIDCollection
    Select New Champion(id, _RRM.returnChampionInformation(id.Substring(0, id.Length() - 1), "na"))
).ToList() ' or ToArray()?

通过添加 AsParallel 可以轻松并行化 LINQ,但您还需要AsOrdered来维护顺序:

_MasterCollection = (
    From id In _MasterIDCollection.AsParallel().AsOrdered()
    Select New Champion(id, _RRM.returnChampionInformation(id.Substring(0, id.Length() - 1), "na"))
).ToList() ' or ToArray()?

默认情况下,PLINQ 将(我相信)每个 CPU 内核运行一个线程,但您可以通过添加 WithDegreeOfParallelism 来控制它。 这是否值得取决于正在完成的工作类型(例如 I/O 绑定或 CPU 绑定):

_MasterCollection = (
    From id In _MasterIDCollection.AsParallel().AsOrdered().WithDegreeOfParallelism(20)
    Select New Champion(id, _RRM.returnChampionInformation(id.Substring(0, id.Length() - 1), "na"))
).ToList() ' or ToArray()?

这需要 .NET 4+,这是对 System.CoreUsing System.Linq 的引用。 有关详细信息,请参阅 PLINQ 文档。

最新更新