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.
(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'm not versed in multithreading, but given that there is no other threading code on this page and nothing r开发者_JAVA技巧eally "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.
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++;
with no risk.
Even better, you can eliminate i
by rewriting as a foreach
instead:
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.
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!
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.
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. If it's just used locally you are fine.
精彩评论