2016-10-17 27 views
1

我有一個返回對象的方法。在我的父函數中,我有一個ID列表。在C#中並行運行方法並整理結果

我想調用每個ID的方法,然後將對象添加到列表中。現在我寫了一個循環,調用傳遞每個ID的方法並等待返回的對象,然後轉到下一個ID。

這可以並行嗎?這裏的任何幫助將是最有幫助的。

+3

像Parallel.ForEach()(MSDN - https://msdn.microsoft.com /de-de/library/system.threading.tasks.parallel.foreach(v=vs.110).aspx)? – Radinator

回答

0

東西:

List<int> ids = new List<int>(); 
    List<object> result = new List<object>(); 
    Parallel.ForEach(ids, (id, state, index) => { 
    result.Add(new { Id = id }); // You class instance here. 
    }); 
0

我覺得任務並行庫將幫助你這個樣子,也許

Task[] tasks = new Task[2]; 
tasks[0] = Task.Factory.StartNew(() => YourFunction()); 
tasks[1] = Task.Factory.StartNew(() => YourFunction()); 
Task.WaitAll(tasks);// here it will wait untill all the functions get completed