I have list of items on which I have to perform big computation task, so I have Implemented the same like following. Please let me know if I am doing any thing wrong here.
{
"MainList": [{
"Name": "First item from root task",
"Task": [{
"SubTask1": "...",
"SubTask2": "..."
}]
},
{
"Name": "Second item from root task",
"Task": [{
"SubTask1": "...",
"SubTask2": "...",
"SubTask3": "...",
"SubTask4": "..."
}]
}
]
}
Scenario:
- Have to perform big computational task on each item from list say T1.
- On completion of any of the task have to perform the another task on each item from same list(this have to perform after T1 gets completed) and in parallel have to perform all the sub tasks from "Tasks" property.
Please note, both the task from STEP 2, have to execute after first task gets completed, and both these task can then execute paralley.
Considering above scenarios, I have developed the code like below:
Code:
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
});
}));
}
Please let me know, if I have did any thing wrong here.
Thanks in Advance!!!