简体   繁体   中英

How to use Parallel.ForEach with a List?

I would like to use Parallel.ForEach with a List but I can't do it.

Here is my current code:

class Test1
{
    public static List<string> myList = new List<string>();

    public object myListToArray()
    {
        return myList.ToArray();
    }
}

class Test2
{
    public void Test(){
        Task.Factory.StartNew(() => Parallel.ForEach(new Test1().myListToArray(), new ParallelOptions { MaxDegreeOfParallelism = 250 }, foo =>
        {
            // do stuff
        }));
    }
}

I'm getting this error:

Unable to derive the type arguments for the 'Parallel.ForEach' method from use. Try to specify the type arguments explicitly.

How can I fix it?

Your existing code doesn't work since Parallel.ForEach doesn't know how to iterate over object (above code) / ArrayList (code in your original post).

public void Test(){
    Task.Factory.StartNew(() => Parallel.ForEach(Test1.myList, new ParallelOptions { MaxDegreeOfParallelism = 250 }, foo =>
    {
        // do stuff
    }));

will work since myList is a generic List , which Parallel.ForEach knows how to handle.

I modified little bit your code, have a look on Test() method,

 class Test1
{
    public static List<string> myList = new List<string>() { "11","22","33"};

    public object myListToArray()
    {
        return myList.ToArray();
    }
}



class Test2
{
    public void Test()
    {
        var test = new Test1();
        Parallel.ForEach((test.myListToArray() as IEnumerable<string>), (value) => { Console.WriteLine(value); });

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM