【发布时间】:2015-02-18 07:04:59
【问题描述】:
关注我之前的question。
在多线程程序中,不同的线程各自生成很长的结果列表。当线程完成它的任务时,我想将不同的列表连接到一个列表中。请注意以下几点:
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 构造函数中为 results 使用 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);
【问题讨论】:
-
您永远不会更新在方法 DoJob() 中定义的变量“results”,因为您通过 VALUE 将它传递给 Functions 的构造函数。一种可能的解决方案是将其初始化为 new List() 而不是 null。
-
@AugustoBarreto 我也尝试了 ref 关键字,但没有成功。 new List() 的初始化迫使我使用 AddRange 而不是 Concat,这在我的应用程序中被认为是高性能损失。跨度>
标签: c# multithreading locking concatenation ienumerable