正確的操作繼我以前question。的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總是空。當線程改變其設置爲_result其他線程發現它空一次。我也嘗試過使用參考關鍵字功能構造函數爲結果,但它沒有改變任何東西。
假設以下按預期執行,我想這可能是我錯過上述代碼的意義呢?!
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(),因爲您是按值將它傳遞給函數的構造函數中定義的變量「結果」。一種可能的解決方案是將其初始化爲新的List()而不是null。 – 2015-02-17 23:06:08
@AugustoBarreto我也試過ref關鍵字,它沒有工作。初始化由一個*新List()*迫使我使用* AddRange *而不是* Concat *,這在我的應用程序中被認爲是一個高性能損失。 – Hamed 2015-02-18 07:12:56