I’m trying to implement multi-threading as suggested here: Spawn Multiple Threads for work then wait until all finished
Code looks like so:
var resetEvent = new ManualResetEvent(false);
var clientsCount = IDLocal.UserSessions.Count;
// Load sessions:
IDLocal.UserSessions = new IDSessions();
// Start thread for each client
foreach (IDSession session in IDLocal.UserSessions)
{
var clnt = session;
new Thread(
delegate()
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
clnt.FailedToRespond = !this.SendDirect(data, this.GetHostAddress(clnt.HostName), clnt.PortNumber);
// If we're the last thread, signal
if (Interlocked.Decrement(ref clientsCount) == 0) resetEvent.Set();
})
.Start();
}
Here I’m getting ReSharper warning: if (Interlocked.Decrement(ref clientsCount) == 0)
It suggests that I’m accessing modified closure (clientsCount)
Is that a valid suggestion?
The warning is meant to cover code such as
where the updated value of
iwill be used when callingf. The warning suggests to change this toif you want
fto see the value ofias it was when the delegate was created. In the context offoreachloops, it is very easy to otherwise get unintuitive behaviour. There has been a change in the meaning offoreachloops in C# 5 because of exactly this.Since that’s not what you want here, since you do want to see changes to the captured variable, don’t change anything in the code.