收集 IronPython 并行循环结果

Collecting IronPython Parallel Loop results

我正在尝试从 IronPython 中的任务方法获得结果,类似于 results.get 与 CPython 的工作方式 multiprocessing.Queue

from System.Threading.Tasks import *
def testThread(dataPnt,constData):
    return dataPnt

def main():

    dataToSplit = range(5)
    constData = 10

    threadResult = Parallel.ForEach(dataToSplit, lambda dataPnt: testThread(dataPnt,constData))

    print(threadResult)

main()

此时 threadResult 是 System.Threading.Tasks.ParallelLoopResult 但我找不到任何合适的文档。最接近的是 this post 但它正在递增,我需要返回一个数组。

Parallel.ForEach is a multi-processing operation but given that you expect a result from your operation you would either have to use a shared result variable (e.g. some sort of concurrent collection) or use a parallel LINQ projection operation.

接近您示例的方法可能如下所示:

# get LINQ dependencies
import clr
clr.AddReference("System.Core")
import System
clr.ImportExtensions(System.Linq)

from System.Threading.Tasks import *
def testThread(dataPnt,constData):
    print dataPnt
    return dataPnt

def main():

    dataToSplit = range(5)
    constData = 10

    threadResult = dataToSplit.AsParallel().Select(lambda dataPnt: testThread(dataPnt,constData)).ToList()

    print(threadResult)

main()