Parallel iteration in C#?

前端 未结 6 1547
耶瑟儿~
耶瑟儿~ 2021-02-06 08:05

Is there a way to do foreach style iteration over parallel enumerables in C#? For subscriptable lists, I know one could use a regular for loop iterati

6条回答
  •  感情败类
    2021-02-06 08:23

    Would this work for you?

    public static class Parallel
    {
        public static void ForEach(IEnumerable[] sources,
                                      Action action)
        {
            foreach (var enumerable in sources)
            {
                ThreadPool.QueueUserWorkItem(source => {
                    foreach (var item in (IEnumerable)source)
                        action(item);
                }, enumerable);
            }
        }
    }
    
    // sample usage:
    static void Main()
    {
        string[] s1 = { "1", "2", "3" };
        string[] s2 = { "4", "5", "6" };
        IEnumerable[] sources = { s1, s2 };
        Parallel.ForEach(sources, s => Console.WriteLine(s));
        Thread.Sleep(0); // allow background threads to work
    }
    

    For C# 2.0, you need to convert the lambda expressions above to delegates.

    Note: This utility method uses background threads. You may want to modify it to use foreground threads, and probably you'll want to wait till all threads finish. If you do that, I suggest you create sources.Length - 1 threads, and use the current executing thread for the last (or first) source.

    (I wish I could include waiting for threads to finish in my code, but I'm sorry that I don't know how to do that yet. I guess you should use a WaitHandle Thread.Join().)

提交回复
热议问题