Adjit
Adjit

Reputation: 10305

Multithreading to open file and update a class object

If I am creating Tasks using a for loop will those tasks run in parallel or would they just run one after the other?

Here is my code -

private void initializeAllSpas()
{
    Task[] taskArray = new Task[spaItems.Count];

    for(int i = 0; i < spaItems.Count; i++)
    {
        taskArray[i] = Task.Factory.StartNew(() => spaItems[i].initializeThisSpa());
    }

    Task.WhenAll(taskArray).Wait();

    foreach (var task in taskArray) task.Dispose();
}

where spaItems is a list of items from another class, call it SpaItem, in which the initializeThisSpa() function opens a file and updates the information for that particular SpaItem.

My question is, does the above code actually excute initializeThisSpa() on all of the spaItems at the same time? if not, how can I correct that?

Upvotes: 0

Views: 52

Answers (1)

Pavan Chandaka
Pavan Chandaka

Reputation: 12751

(I Ignored syntax issues if any and not tested)

At the same time?..

Not guaranteed. At least (the best bet) definitely there will be nano secs difference.

Tasks are placed in a queue.

And every task waits for its opportunity for a thread from threadpool, for its turn of execution.

It all depends on the availability of threads in thread pool. If no thread available, the tasks waits in queue.

There are different states for the task before its final execution. Here is a good explanation. And after going through this link, you will come to know that it is almost impossible to call a function at the same time from multiple tasks.

https://blogs.msdn.microsoft.com/pfxteam/2009/08/30/the-meaning-of-taskstatus/

You can achieve tasks sequentially (one after another) calling a specific function by creating tasks with methods like "ContinueWith, ContinueWhenAll, ContinueWhenAny,"

An example is below in MSDN documentation link.

https://msdn.microsoft.com/en-us/library/dd321473(v=vs.110).aspx

Upvotes: 2

Related Questions