我正在尝试按照此处的建议实现多线程:Spawn Multiple Threads for work then wait until all finished
代码如下所示:
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();
}
在这里,我收到 ReSharper 警告:if (Interlocked.Decrement(ref clientsCount) == 0)
它表明我正在访问修改后的闭包(clientsCount)
这是一个有效的建议吗?