繁体   English   中英

正确处理IEnumerable <foo>

[英]Proper manipulation of IEnumerable<foo>

继我之前的问题

在多线程程序中,不同的线程各自生成非常长的结果列表。 当线程完成任务时,我想将不同的列表连接到一个列表中。 请注意以下几点:

public struct AccEntry
{
    internal AccEntry(int accumulation)
        : this()
    {
        Accumulation = accumulation;
    }
    public int Accumulation { private set; get; }
}


internal class Functions
{
     internal Functions(Object lockOnMe, IEnumerable<AccEntry> results)
     {
          _lockOnMe = lockOnMe;
          _results = results;
          _result = new List<AccEntry>();
     }

     private IEnumerable<AccEntry> _results { set; get; }
     private List<AccEntry> _result { set; get; }

     internal void SomeFunction()
     {
          /// some time consuming process that builds _result
          lock(_lockOnMe)
          {
              /// The problem is here! _results is always null.
              if (_results == null) _results = _result;
              else _results = _results.Concat(_result);
          }
     }
}

public class ParentClass
{
     public void DoJob()
     {
          IEnumerable<AccEntry> results = null;
          /// initialize and launch multiple threads where each 
          /// has a new instance of Functions, and call SomeFunction.
     }
}

如代码中所述,问题是_results始终为null 当线程更改时,将其设置为_result ,另一个线程再次将其查找为null 我还尝试在Functions构造函数中为结果使用ref关键字,但它没有任何改变。

假设后续执行按预期执行,我想知道我在上述代码上缺少的重点是什么!!

List<int> listA = new List<int>();
List<int> listB = new List<int>();
listA.Add(10);
listB.Add(12);
IEnumerable<int> listC = null;
listC = listA;
listC = listC.Concat(listB);

当您串联各项并将其分配回_results变量时,它将替换您分配给该变量的原始值。 新的项目集合将在该实例本地。

不必使用必须替换的IEnumerable<>来更新它,而使用可以在其中添加项目的List<>

internal class Functions
{
     internal Functions(Object lockOnMe, List<AccEntry> results)
     {
          _lockOnMe = lockOnMe;
          _results = results;
          _result = new List<AccEntry>();
     }

     private object _lockOnMe;
     private List<AccEntry> _results;
     private List<AccEntry> _result;

     internal void SomeFunction()
     {
          /// some time consuming process that builds _result
          lock(_lockOnMe)
          {
              _results.AddRange(_result);
          }
     }
}

只需确保在创建Functions实例之前创建列表即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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