Álvaro García
Álvaro García

Reputation: 19396

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

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?

Upvotes: 0

Views: 683

Answers (1)

spender
spender

Reputation: 120548

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

Upvotes: 3

Related Questions