Tasks show the same irration in the cycle - C#



  • Good evening, trying with the Task Force to set up several processes and start a function in each one, but it always gets the same irration. This is the example of the code:

     var Task_1 = Task.Factory.StartNew(() =>
                 {
                     for (var i = 0; i < 7; i++)
                     {
                         Task.Factory.StartNew(() =>
                         {
                             Console.WriteLine(i);
    
                         //Task.Factory.StartNew(matrix.Multiplication, i, TaskCreationOptions.AttachedToParent);
    
                     }, TaskCreationOptions.AttachedToParent);
    
                 }
             });
    
            Task.WaitAll(Task_1);
    

    There are no 7 different numbers in any sequence on the screen, with one fourth and all the other seven. Can you explain to anyone what the problem is and how do you get over it? I tried in the cycle to expect the completion of each process (measure: task.Wait()), but then the task is not parallel.



  • The problem is, ivariable! Which means her meaning changes. When the task begins, the importance i It's quite possible to change. And you're gonna get the same variable all the time. i

    I would have written that:

    Task Output(int i)
    {
        return Task.Run(() => Console.WriteLine(i));
    }
    

    var tasks = new List<Task>();
    for (int i = 0; i < 7; i++)
    tasks.Add(Output(i));
    await Task.WhenAll(tasks);

    Importance i copied at the time the function was called.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2