Task.Run(() => - order of processing ......multithreading in foreach loop?

Hi, I have a question about the order of the code is processed in multi threaded envrioment


I have a bunch of cars with tracking data
I need to look at each cars tracking record (ordered by datetime) and do some stuff (it HAS to be processed in datetime order - one at a time)

This was way to slow, so now i've made the app multithreaded,
I've essentially got
GROUPS - (each item in group is 1 car)
POSITIONS - (all the cars positions data in right order)

i.e.
GROUPS
--Car 1
-----All Car 1 Positions

--Car 2
-----All Car 2 Positions

etc

In my code I have this working, but i'm not sure if they will be processed as I want
i.e. I need car 1 and car 2 etc to be processed at same time of different threads, but their POSITION data to be processed 1 at a time in right order
consider the following code

foreach (var car in GroupOfCarsAndPositions.ToList())
{

                    Task.Run(() =>
                    {
                       //each car should be processed at the same time (multithreaded)

                        foreach (var position in car.PositionsList.ToList())
                        {
                              //each position  Item in this group should be processed one at a time
                         }
                     }
}

Open in new window


my question is, will the first foreach be processed multithreaded? (i.e. each car be processed at same time?)
websssAsked:
Who is Participating?
 
sarabandeCommented:
will the first foreach be processed multithreaded?
no, the first foreach will run in the main thread and create tasks for each car sequentially in the loop.  then, each task will run asynchronously (that is what you expected) and perform the second loop. but, after the first foreach you may have to wait for the tasks to finish in order to evaluate the results. alternatively, your main thread may run a gui and process the results of the tasks within the gui.

Sara
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
Simplest if you need them to be processed in order then you must do the processing in the same thread.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.