Parallel.Foreach + yield return?

后端 未结 5 1422
执笔经年
执笔经年 2020-12-16 10:50

I want to process something using parallel loop like this :

public void FillLogs(IEnumerable computers)
{
    Parallel.ForEach(computers, cp         


        
5条回答
  •  攒了一身酷
    2020-12-16 11:07

    How about

                Queue qu = new Queue();
                bool finished = false;
                Task.Factory.StartNew(() =>
                {
                    Parallel.ForEach(get_list(), (item) =>
                    {
                        string itemToReturn = heavyWorkOnItem(item);         
                        lock (qu)
                           qu.Enqueue(itemToReturn );                        
                    });
                    finished = true;
                });
    
                while (!finished)
                {
                    lock (qu)
                        while (qu.Count > 0)
                            yield return qu.Dequeue();
                    //maybe a thread sleep here?
                }
    

    Edit: I think this is better:

            public static IEnumerable ParallelYieldReturn(this IEnumerable source, Func func)
            {
                ConcurrentQueue qu = new ConcurrentQueue();
                bool finished = false;
                AutoResetEvent re = new AutoResetEvent(false);
                Task.Factory.StartNew(() =>
                {
                    Parallel.ForEach(source, (item) =>
                    {
                        qu.Enqueue(func(item));
                        re.Set();
                    });
                    finished = true;
                    re.Set();
                });
    
                while (!finished)
                {
                    re.WaitOne();
                    while (qu.Count > 0)
                    {
                        TOutput res;
                        if (qu.TryDequeue(out res))
                            yield return res;
                    }
                }
            }   
    

    Edit2: I agree with the short No answer. This code is useless; you cannot break the yield loop.

提交回复
热议问题