线程奇怪的地方?

kav*_*man 1 c# asp.net multithreading

我正在维护一些现有的页面,并且遇到了一些代码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);
    }
}
Run Code Online (Sandbox Code Playgroud)

做这样的事情有意义吗?不能i增加ala i++而不是?我不熟悉多线程,但鉴于此页面上没有其他线程代码,并且没有真正"特殊"发生(没有创建额外的线程等),对我来说似乎有点奇怪.

谢谢你的协助!

Jul*_*iet 7

你的直觉是正确的-该代码有点怪怪的,很可能会成为一个好提交的DailyWTF.

我不确定原始开发人员的动机,但没有任何其他上下文,该方法似乎是线程安全的.您应该能够无风险地增加i使用i++;.

更好的是,您可以i通过重写来消除foreach:

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
    }
}
Run Code Online (Sandbox Code Playgroud)