2017-01-10 65 views
0

我有一个方法,我想运行多个线程来更快地完成它。多线程开始按顺序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开始所有类型的数字。我的主要是这样的:

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循环,它似乎也没有工作。有谁知道如何以任何方式做这项工作?

回答

2

你可以转换您当前的代码使用LINQ到您_MasterIDCollectionChampion实例映射:加入AsParallel

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

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 docs

+0

谢谢你,我在另一个网站上阅读过它,但你的例子帮助我更好地理解它。 –

+0

我跑过了你的答案,而且效果很好。但是,在4,000个新对象之后,应用程序开始爬行并崩溃。任何想法处理它的最佳方式? –

+0

@RalphMaurmeier不知道'_RRM.returnChampionInformation'和'Champion'构造函数在做什么,我只能推测。你有没有指定'WithDegreeOfParallelism',以及具有什么价值?当应用程序开始抓取并崩溃时,是否存在高CPU和/或内存使用率?如果不平行运行(即第一个例子),会发生什么? – Mark