コードで「メモリ不足の例外」が発生することがあります。これは、並列ループを実行してから 5 分または 10 分後にランダムに発生します。File.ReadAllLines(line)で例外がスローされます。キャッシュ タイマーを無効にすると、すべて正常に動作します。5秒ごとに読み取る190MBのファイルが2つあります。私のアプリケーションからのコード部分:
class MC {
private readonly ConcurrentDictionary<string, Lazy<string[]>> _files = new ConcurrentDictionary<string, Lazy<string[]>>();
private readonly Timer _cache = new Timer();
private MC ()
{
_cache.Enabled = true;
_cache.Interval = (int) Settings.Default.fileCache*1000; //seconds
_cache.Elapsed += (sender, args) => _files.Clear();
_cache.Start();
Parallel.ForEach(lines, options, (line, loopState, idx) =>
{
//code
string[] resultStrings = {};
var fileKey = GetMD5Hash(line);
resultStrings = _files.GetOrAdd(fileKey, new Lazy<string[]>(() => File.ReadAllLines(line),
LazyThreadSafetyMode.ExecutionAndPublication)).Value;
Fun(string.Join("", resultStrings.OrderBy(x => GetThreadRandom().Next()).Take(10))); //code
}
}
}
parallel lopp からの行は次のようになります (100 000 000 のレコードがあります):
c:\a.txt
c:\b.txt
c:\a.txt
c:\b.txt
c:\a.txt
c:\b.txt
c:\a.txt
c:\b.txt
c:\a.txt
c:\b.txt
c:\a.txt
c:\b.txt