Elad Winkler
Elad Winkler

Reputation: 700

Parallel.For looping on the same value

I'm trying to make a simple parallel.For and It seems to be getting the same "i" over and over again.
My code is:

String[] str = new String[10000];

Parallel.For(0,10000, i=>

{

if(str[i] == string.Empty)

   str[i] = "ok";

else

   str[i] = "SameValue";

});

I would expect it to never get to "else"

Upvotes: 0

Views: 103

Answers (2)

Chris Diver
Chris Diver

Reputation: 19802

string.Empty does not equal null, change your if condition to

if (String.IsNullOrEmpty(str[i]))

Upvotes: 3

BrokenGlass
BrokenGlass

Reputation: 160852

I would expect it to never get to "else"

Wrong - the string array elements are initialized with null (their default value as reference type) - not string.Empty. Hence only the else part is ever executed.

You can easily verify this yourself by setting a break point on the if statement.

Upvotes: 2

Related Questions