Parallel iteration in C#?

前端 未结 6 1560
耶瑟儿~
耶瑟儿~ 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:40

    .NET 4's BlockingCollection makes this pretty easy. Create a BlockingCollection, return its .GetConsumingEnumerable() in the enumerable method. Then the foreach simply adds to the blocking collection.

    E.g.

    private BlockingCollection m_data = new BlockingCollection();
    
    public IEnumerable GetData( IEnumerable> sources )
    {
        Task.Factory.StartNew( () => ParallelGetData( sources ) );
        return m_data.GetConsumingEnumerable();
    }
    
    private void ParallelGetData( IEnumerable> sources )
    {
        foreach( var source in sources )
        {
            foreach( var item in source )
            {
                m_data.Add( item );
            };
        }
    
        //Adding complete, the enumeration can stop now
        m_data.CompleteAdding();
    }
    

    Hope this helps. BTW I posted a blog about this last night

    Andre

提交回复
热议问题