我正在尝试按照此处的建议实现多线程: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 clientCount) == 0)
它表明我正在访问修改后的闭包(clientsCount)
这是一个有效的建议吗?
最佳答案
该警告旨在涵盖以下代码
int i = 1;
Func<int> f = () => i + 1;
i = 2;
int j = f(); // What does this set j to?
调用f
时将使用i
的更新值。该警告建议将其更改为
int i = 1;
int icopy = i;
Func<int> f = () => icopy + 1;
i = 2;
int j = f(); // Now what does this set j to?
如果您希望f
看到i
创建委托(delegate)时的值。在 foreach 循环的上下文中,很容易出现不直观的行为。正因为如此,C# 5 中 foreach
循环的含义发生了变化。
因为这不是您想要的,因为您确实希望看到捕获的变量的更改,所以不要更改代码中的任何内容。
关于c# - 启动和等待多个线程 - Resharper 提示修改后的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12521392/