How to execute each iteration of the loop in one thread with task?

主宰稳场 提交于 2021-02-17 06:53:09

问题


I have a method that check some data and I would like to know how to check this data in differents threads. I am using task and async/await pattern.

private bool my myCheckMethod(List<long> paramData)
{
     //code that check the information in the list
}


private void mainMethod()
{
    //1.- get data from the data base
    //2.- i group the data from the database in many lists.

    foreach(list<List<long>> iterator in myListOfLists)
    {
          myCheckMethod(itrator);
    }
}

But I would like that the myCheckMethod not execute only one at time, but to use tasks to execute many at same time. I think that it would take less time.

However, I don't know well how to do that. I try something like that:

private void mainMethod()
{
    //1.- get data from the data base
    //2.- i group the data from the database in many lists.

    string initTime = System.DateTime.String();
    foreach(list<List<long>> iterator in myListOfLists)
    {
          myCheckMethod(itrator);
    }

    string endTime = System.DateTime.String();
}

I would like to have information when the check is started and when all the lists are checked.

I try something like that:

private void mainMethod()
    {
        //1.- get data from the data base
        //2.- i group the data from the database in many lists.

        string startTime = System.DateTime.String();
        foreach(list<List<long>> iterator in myListOfLists)
        {
             TaskEx.Run(() =>
             {
                myCheckMethod(itrator);
             });
        }

        string endTime = System.DateTime.String();
    }

But in this case start time and end time is the same, because I don't await the task. So I try this other option:

private void mainMethod()
    {
        //1.- get data from the data base
        //2.- i group the data from the database in many lists.

        string startTime = System.DateTime.String();
        foreach(list<List<long>> iterator in myListOfLists)
        {
             TaskEx.Run(() =>
             {
                myCheckMethod(itrator);
             }).wait();
        }

        string endTime = System.DateTime.String();
    }

But in this case only is executed one myCheckMethod at the same time, because I am wating to finish one to continue with the next iteration.

So how can I execute many check methods at the same time?


回答1:


var sw = Stopwatch.StartNew();
var pendingTasks =
  myListOfLists
    .Select(iterator => TaskEx.Run(() => myCheckMethod(iterator))).ToArray();
Task.WaitAll(pendingTasks);
var elapsedTime = sw.Elapsed;


来源:https://stackoverflow.com/questions/19447509/how-to-execute-each-iteration-of-the-loop-in-one-thread-with-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!