0 Comments
  •   Posted in: 
  • Task

When you have a simple for each loop in your code, sometimes it's possible to make the loop faster by using Tasks. The idea is to create a task for every item in the loop. You start the task when you go over it. After the loop finishes you will wait for all the tasks to finish and you are good to go..

This is an example of an optimized loop:

// Get the collection
var dataCollection = GetCollection();

// Create a list to keep track all tasks
var tasks = new List<Task>();

// Check all entries
foreach (var entry in data Collection)
{

     // Create a task and execute it immediately
     var t =Task.Run(() =>
     {

       // Do your thing here

      });

      // Add the task to keep track of it
      tasks.Add(t);

}

// Wait for all tasks to complete
Task.WaitAll(tasks.ToArray());

When you have a lot of items in your collection the benefits will increase.

Post comment