gpt4 book ai didi

c# - 启动并等待多个线程 - Resharper 提示修改关闭

转载 作者:行者123 更新时间:2023-11-30 22:24:54 27 4
gpt4 key购买 nike

我正尝试按照此处的建议实现多线程: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)

这是一个有效的建议吗?

最佳答案

该警告旨在覆盖诸如

之类的代码
int i = 1;
Func<int> f = () => i + 1;
i = 2;
int j = f(); // What does this set j to?

i 的更新值将在调用 f 时使用。警告建议将其更改为

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com