[英]How to handle/implement multiple Tasks in C#
我有必須執行大型計算任務的項目列表,因此我實現了類似以下內容的項目。 如果我在這里做錯了任何事情,請告訴我。
{
"MainList": [{
"Name": "First item from root task",
"Task": [{
"SubTask1": "...",
"SubTask2": "..."
}]
},
{
"Name": "Second item from root task",
"Task": [{
"SubTask1": "...",
"SubTask2": "...",
"SubTask3": "...",
"SubTask4": "..."
}]
}
]
}
場景:
請注意,STEP 2中的兩個任務都必須在第一個任務完成后執行,然后這兩個任務都可以執行並行處理。
考慮到以上情況,我開發了如下代碼:
碼:
List<Task<object>> mainFirstTaskList = new List<Task<object>>();
List<Task<object>> mainSecondTaskList = new List<Task<object>>();
List<Task> subTaskList = new List<Task>();
foreach (var itm in MainList)
{
mainFirstTaskList.Add(Task.Factory.StartNew<object>(() =>
{
//Use "itm" from iteration
//Perform big computational task on each item
return resultFirstMainList;
}));
}
while (mainFirstTaskList.Count > 0)
{
int finishedTask = Task.WaitAny(mainFirstTaskList.ToArray()); //waiting for any of the task to gets complete
Task<object> t = mainFirstTaskList[finishedTask];
var result = t.Result;
//Perform Another Task on the same list
mainSecondTaskList.Add(Task.Factory.StartNew<object>(() =>
{
//use result from first task completed
//Perform big computational task on each item
return resultSecondMainList;
}));
//Perform the task on sub item list
subTaskList.Add(Task.Factory.StartNew<object>(() =>
{
//Have used Parallel.For to partition the sub task computation
//And have added this Parallel.For inside another Task, as Parallel.For will partition the tasks on current thread
Parallel.For(1, subItemIndex, i =>
{
//Perform big task computation
});
}));
}
如果我在這里做錯了什么,請告訴我。
提前致謝!!!
我想我大致了解您在做什么。 您應該為此使用Microsoft的Reactive Framework。 然后,您可以執行以下操作:
var query =
from mainItem in MainList.ToObservable()
from firstResult in Observable.Start(() => ProcessMainItem(mainItem))
from secondResult in Observable.Start(() => ProcessFirstItem(firstResult))
from subItem in secondResult.ToObservable()
from result in Observable.Start(() => ProcessSubItem(subItem))
select result;
IDisposable subscription =
query
.Subscribe(x =>
{
/* Process results as they are computed */
});
每次計算都是並行進行的,並且將結果匯總到最終結果中。
您甚至可以select new { mainItem, firstResult, secondResult, subItem, result };
一個select new { mainItem, firstResult, secondResult, subItem, result };
如果您想將所有中間結果聯系在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.