For loop goes out of range

后端 未结 3 597
滥情空心
滥情空心 2020-12-16 12:29
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        sta         


        
3条回答
  •  有刺的猬
    2020-12-16 13:10

    Using foreach does not throw:

    foreach (var i in arr)
    {
      Task.Factory.StartNew(() => WorkerMethod(i));
    }
    

    But is doesn't work either:

    101
    101
    

    It executes WorkerMethod with the last entry in the array. Why is nicely explained in the other answers.

    This does work:

    Parallel.ForEach(arr, 
                     item => Task.Factory.StartNew(() => WorkerMethod(item))
                     );
    

    Note

    This actually is my first hands-on experience with System.Threading.Tasks. I found this question, my naive answer and especially some of the other answers useful for my personal learning experience. I'll leave my answer up here because it might be useful for others.

提交回复
热议问题