In web api controller: I am a newer in parallel and Async&Task programming. Need someone help me code review.
public async Task<IHttpActionResult> DoWork()
{
List<string> listTask = await Helper.GetBlockBlock();
userIds = listTask;
this.ParallelTaskWork();//step 1,must be finished,but I an not sure when..
await this.Service.GetAllClientInterestInfoList();//executing after step 1
return this.Ok();
}
public async void ParallelTaskWork()
{
Task[] taskList = this.TaskMaker(totalNum);
}
public Task[] TaskMaker(int threadNum)
{
Task[] taskList = new Task[threadNum];
Parallel.For(0, taskList.Length, i => taskList[i] = new Task(this.ProcessDealTask));
Parallel.ForEach(taskList, t => t.Start());
return taskList;
}
private void ProcessDealTask()
{
for (int i = 0; i < totalNum; i++)
{
List<string> users = this.GetPartitionOfList(userIds, i, totalNum);
Task task = this.ParallelDealUserList(users);
task.Wait();
}
}
private List<T> GetPartitionOfList<T>(List<T> userList, int index, int total)
{
int section = (userList.Count / total) + 1;
int end = (index + 1) * section > userList.Count ? userList.Count - index * section : section;
if (end < 0) end = 0;
int start = index * section < userList.Count ? index * section : userList.Count - 1;
if (start < 0) start = 0;
return userList.GetRange(start, end);
}
private async Task ParallelDealUserList(IEnumerable<string> list)
{
await Task.Run(() => Parallel.ForEach(list, async (id, loopState) =>
{
try
{
await GrainClient.GrainFactory.GetGrain<IUser>(id.ToGuid()).DoProcessInterestAsync(true);
}
catch (Exception e)
{
}
}));
}
Any performance problem? The method ParallelDealUserList I refer to https://stackoverflow.com/questions/19102966/parallel-foreach-vs-task-run-and-task-whenall somebody said
there is a disadvantage to use Task.Run in a loop- With Parallel.ForEach, there is a Partitioner which gets created to avoid making more tasks than necessary
and The method TaskMaker https://stackoverflow.com/questions/22988630/parallel-for-w-action-that-creates-different-tasks-c-sharp