Have had a bit of a search, but couldn’t find the same situation I’m facing here.
Here’s the snippet I’m worried about:
var threadsafeVacantStats = new Dictionary<Thread, StatsNode>();
var threadSafeVacantLocker = new Object();
var threadsafeZoneStats = new Dictionary<Thread, StatsNode>();
var threadSafeZoneLocker = new Object();
Parallel.ForEach(m_TeamAreasByZone[zone.ContainerID], team =>
{
var tempVacantStatNode = CreateASyncStatsNodes(threadSafeVacantLocker, threadsafeVacantStats);
var tempZoneStatNode = CreateASyncStatsNodes(threadSafeZoneLocker, threadsafeZoneStats);
//...other stuff
}
Here’s the function it’s calling:
private static StatsNode CreateASyncStatsNodes(object threadSafeLocker, Dictionary<Thread, StatsNode> threadsafeTeamStats)
{
StatsNode tempStatsNode;
var currentThread = Thread.CurrentThread;
lock (threadSafeLocker)
{
if (!threadsafeTeamStats.ContainsKey(currentThread))
threadsafeTeamStats[currentThread] = new StatsNode(0, 0);
tempStatsNode = threadsafeTeamStats[currentThread];
}
return tempStatsNode;
}
To me, this looks fine, however resharper is giving a warning for the second call to CreateASyncStatsNodes (the first call is fine).
Following its advice, it turns the block into:
var threadsafeVacantStats = new Dictionary<Thread, StatsNode>();
var threadSafeVacantLocker = new Object();
var threadsafeZoneStats = new Dictionary<Thread, StatsNode>();
var threadSafeZoneLocker = new Object();
object locker = threadSafeZoneLocker;
Dictionary<Thread, StatsNode> stats = threadsafeZoneStats;
Parallel.ForEach(m_TeamAreasByZone[zone.ContainerID], team =>
{
var tempVacantStatNode = CreateASyncStatsNodes(threadSafeVacantLocker, threadsafeVacantStats);
var tempZoneStatNode = CreateASyncStatsNodes(locker, stats);
//...
}
This doesn’t really make sense to me, and doesn’t seem to actually fix anything (if it was even broken in the first place). Is resharper mistakenly marking giving a warning, or am I missing something?
Resharper doesn’t know that Parallel.ForEach execute passed lambda immediately. It suppose that this lambda could be executed later, when closure will be modified and this could produce some problems. You can ignore this warning.