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 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.
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
iusingi++;with no risk.Even better, you can eliminate
iby rewriting as aforeachinstead: