Please read and understand this:
http://en.wikipedia.org/wiki/Race_condition[
^].
Also, you should understand that your list is a shared object. Generally, if add elements to it using
lock statement.
If you use
System.Generic.List<>
, you should declare
list
as
System.Generic.List<int>
, not just as
List
(what is that?).
Any instance members are not guaranteed to be thread safe.
Therefore, use the lock:
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx[
^].
I cannot tell you how to correct your code because I don't know your goal. If your goal was to illustrate
race condition, different results in different runs of the code would be exactly what you needed. Only write it correctly and add the lock. Having the different results is just the nature of your algorithm.
—SA