0
實現多任務我有,我有執行大運算任務物品的清單,所以我已經實現像以下同。 如果我在這裏做錯了任何事情,請讓我知道。如何處理/ C#中
{
"MainList": [{
"Name": "First item from root task",
"Task": [{
"SubTask1": "...",
"SubTask2": "..."
}]
},
{
"Name": "Second item from root task",
"Task": [{
"SubTask1": "...",
"SubTask2": "...",
"SubTask3": "...",
"SubTask4": "..."
}]
}
]
}
場景:
- 不得不從列表中每個項目執行大的計算任務說T1。
- 在任何任務的完成必須從同一列表中每個項目執行其他任務(這有T1被完成後執行) 和並行必須從「任務」 財產執行所有的子任務。
請注意,這兩個步驟2中的任務,必須首先得到任務完成後執行,然後這兩個任務可以執行paralley。
考慮到上述情況,我已經開發了類似下面的代碼:
代碼:
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
});
}));
}
請讓我知道,如果我錯在這裏做任何事情。
在此先感謝!
謝謝@Enigmativity,我對微軟的Reactive非常新穎,期望首先開始「mainFirstTaskList」任務,並且隨着任務逐一完成,必須逐一啓動「mainSecondTaskList」和「subTaskList」,因爲它們是獨立的每一個。 在「subTaskList」中,有多個任務使用了Parallel.For。 什麼你寫的所有任務將在平行的,但兩者「mainSecondTaskList」和「subTaskList」開始依賴於從「mainFirstTaskList」的結果。 我在執行過程中是否有任何問題? –
@GaneshChoudhari - 您需要爲我提供一個[mcve]來評論您的代碼是否有效。很難完全理解部分代碼。你應該嘗試我的方法 - 你會驚訝它處理多線程的能力。 – Enigmativity