0

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?

2
  • 1
    Why do you need to use async/await, if you don't need a result anyway? Can't you simply use Parallel.ForEach ? Commented Oct 18, 2013 at 10:51
  • Your code doesn't use async/await anywhere. Besides, async/await doesn't cause code to run asynchronously, it waits on already started asynchronous operations. Commented Oct 18, 2013 at 11:12

1 Answer 1

3
var sw = Stopwatch.StartNew(); var pendingTasks = myListOfLists .Select(iterator => TaskEx.Run(() => myCheckMethod(iterator))).ToArray(); Task.WaitAll(pendingTasks); var elapsedTime = sw.Elapsed; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.