multithreading - C# static constructor initialization thread safety while filling ConcurrentDictionary -
i'm calling var person = persondb.pdict["395096"];
can explain me why code blocks:
static class persondb { internal static readonly concurrentdictionary<string, person> pdict; static persondb() { pdict = new concurrentdictionary<string, person>(); var headers = file.readlines(findpath.datasetperson).first().split(';'); file.readlines(findpath.datasetperson).asparallel().skip(1).select(s => s.split(';')).forall(fa => pdict.tryadd(fa[0], new person() { = enumerable.range(0, fa.length).todictionary(t => headers[t], d => fa[d]) }) ); } } sealed class person { public dictionary<string, string> all; }
while part not block:
static class persondb { internal static readonly concurrentdictionary<string, person> pdict; static persondb() { pdict = new concurrentdictionary<string, person>(); var headers = file.readlines(findpath.datasetperson).first().split(';'); //file.readlines(findpath.datasetperson).asparallel().skip(1).select(s => s.split(';')).forall(fa => // pdict.tryadd(fa[0], new person() { = enumerable.range(0, fa.length).todictionary(t => headers[t], d => fa[d]) }) //); parallel.foreach(file.readlines(findpath.datasetperson).skip(1).select(s => s.split(';')), line => { pdict.tryadd(line[0], new person() { = enumerable.range(0, line.length).todictionary(t => headers[t], d => line[d]) }); }); } } sealed class person { public dictionary<string, string> all; }
to honest i'm not sure if latter thread safe now, @ least runs without problems. know how make persondb thread safe class in such way there no race conditions or deadlocks. pdict needs created once on usage of pdict. thought static constructor nice solution execution stop on plinq query makes me unsure...
this static constructor deadlock. parallel threads access persondb
blocks until persondb
statically initialized. move initialization code different function. make return dictionary instead of modifying pdict
in place.
i try avoid static constructors things can fail. code can fail because io. if class permanently hosed. lazy
can better.
Comments
Post a Comment