Mahmoud Samy
Mahmoud Samy

Reputation: 2852

Creating Tasks inside a loop

Is it possible to create Tasks inside a loop like this:

List<Task<string>> tasks = new List<Task<string>>();
for (int id = 0; id < 1000; id++)
{
    tasks.add(new Task<string>((tId) =>
        {
            var taskId = (int)tId;
            var rand = new Random(taskId);
            long sum = 0;
            for (int i = 0; i < 100000; i++)
            {
                sum += rand.Next(1000);
            }
            return string.Format("Task {0}: {1}", taskId, sum) ;
        }, id));
}

Then start all tasks like this:

foreach (var task in tasks)
{
    task.Start();
}

Then wait for all to finish:

Task.WaitAll(tasks.ToArray());

Then harvest the results:

foreach (var task in tasks)
{
    Console.WriteLine(task.Result);
}

This code is working but I can't control the degree of parallelism (number of max threads). and I don't know if this practice is right or not?

Upvotes: 2

Views: 2189

Answers (1)

Venson
Venson

Reputation: 1870

This MSDN artical describes how to Override the Task Scheduler class to reach that what you want. It is called LimitedConcurrencyLevelTaskScheduler but a Small advice ... i have worked 2 Months to get a Absolutely save working and Fast solution for my Requirements so you have to investigate a LOT of time in this Task! You should consider about other solutions for that Problem.

Btw you can take a look into the PLinq lib and the MaxDegreeofParallelism property. But as a mircosoft developer has told me in a Seminar. Don't do that!. The Task lib and the PLinq lib is Highly optimized in that field so if you change that you will get a gigantic Performance issue

Upvotes: 2

Related Questions