我正在维护一些现有页面,并从 System.Threading
中遇到了一些代码,但我不确定该怎么做。
(这是它的要点)
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDoc = GetFromCMS();
var nodes = xmlDoc.SelectNodes("/xpath/to/nodes");
int i = 0;
while (i < nodes.Count)
{
//do stuff with nodes[i]
//last line in while loop - this is where I'm confused
Math.Max(System.Threading.Interlocked.Increment(ref i), i - 1);
}
}
这样做有意义吗? i
不能增加 ala i++
吗?我不精通多线程,但鉴于此页面上没有其他线程代码并且没有真正“特殊”的事情发生(没有创建额外的线程等),这似乎有点奇怪我。
感谢您的协助!
最佳答案
您的直觉是正确的——代码有点奇怪,可能会很好地提交给The DailyWTF .
我不确定最初开发人员的动机,但在没有任何其他上下文的情况下,该方法似乎是线程安全的。您应该能够使用 i++;
增加 i
而没有风险。
更好的是,您可以通过重写为 foreach
来消除 i
:
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDoc = GetFromCMS();
var nodes = xmlDoc.SelectNodes("/xpath/to/nodes");
foreach(var node in nodes)
{
//do stuff with node
}
}
关于c# - 线程的奇怪地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6132702/