简体   繁体   English

穿线的奇怪地方?

[英]Strange place for threading?

I'm maintaining some existing pages and came across a bit of code from System.Threading and I'm not sure what to make of it.我正在维护一些现有页面,并从System.Threading中发现了一些代码,但我不知道该怎么做。

(this is a the gist of it) (这是它的要点)

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);
    }
}

Does it makes sense to do something like this?做这样的事情有意义吗? Couldn't i be incremented ala i++ instead?难道i不能增加 ala i++吗? I'm not versed in multithreading, but given that there is no other threading code on this page and nothing really "special" happening (no extra threads being created, etc), it seems a little strange to me.我不精通多线程,但鉴于此页面上没有其他线程代码并且没有发生真正“特殊”的事情(没有创建额外的线程等),这对我来说似乎有点奇怪。

Thanks for your assistance!感谢你的协助!

Your intuition is correct -- the code is a little strange, would probably make a good submission to The DailyWTF .你的直觉正确的——代码有点奇怪,可能会很好地提交给DailyWTF

I'm not sure of the original developers motives, but without any other context, the method appears to be threadsafe.我不确定最初开发人员的动机,但没有任何其他上下文,该方法似乎是线程安全的。 You should be able to increment i using i++;您应该能够使用i++;增加i with no risk.没有风险。

Even better, you can eliminate i by rewriting as a foreach instead:更好的是,您可以通过重写为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
    }
}

i is a local variable (and not shared with any other threads), so a simple i++ is safe. i是一个局部变量(不与任何其他线程共享),因此简单的i++是安全的。

So, replace this:所以,替换这个:

Math.Max(System.Threading.Interlocked.Increment(ref i), i - 1);

with this有了这个

i++;

Or as a commenter pointed out, replace with a simple for or foreach loop!或者正如评论者指出的那样,用简单forforeach循环替换!

Unless you are sharing the local i variable with other threads somehow (highly doubtful), i++ would work just as well, without the overhead of the interlocking increment function.除非您以某种方式与其他线程共享本地i变量(非常值得怀疑),否则i++也可以正常工作,而不会产生联锁增量 function 的开销。

The only way I could see that happening is if you are passing i by reference within the body of the loop to another function, which would then share it.我能看到这种情况发生的唯一方法是,如果您在循环体内通过引用将i传递给另一个 function,然后它将共享它。 If it's just used locally you are fine.如果只是在本地使用,那就没问题了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM