Wednesday 30 November 2016

.Net High Performance Part 7 : Correctly passing Parameters into a Task

If we are going to use some shared variables inside a Task, we might not refer the correct values because of race conditions.  Following is an example.


for(int i=0;i<10;i++)
{
    Task.Factory.StartNew( () =>
   {
       int id = i;
       Console.WriteLine(id);          
   }                      
   );
}

for(int i=0;i<10;i++)
{
    Task.Factory.StartNew( (arg) =>
   {

       int id = (int) arg;
       Console.WriteLine(id);
   },
    i     // Passing in the param                              
   );

}

No comments:

Post a Comment