Please check the sample code below:
public class Sample { public int counter { get; set; } public string ID; public void RunCount() { for (int i = 0; i < counter; i++) { Thread.Sleep(1000); Console.WriteLine(this.ID + " : " + i.ToString()); } } } class Test { static void Main() { Sample[] arrSample = new Sample[4]; for (int i = 0; i < arrSample.Length; i++) { arrSample[i] = new Sample(); arrSample[i].ID = "Sample-" + i.ToString(); arrSample[i].counter = 10; } foreach (Sample s in arrSample) { ThreadPool.QueueUserWorkItem(callback => s.RunCount()); } Console.ReadKey(); } }
The expected result for this sample should look something like this:
Sample-0 : 0 Sample-1 : 0 Sample-2 : 0 Sample-3 : 0 Sample-0 : 1 Sample-1 : 1 Sample-2 : 1 Sample-3 : 1 . . .
However, when you run this code, instead it will look something like this:
Sample-3 : 0 Sample-3 : 0 Sample-3 : 0 Sample-3 : 1 Sample-3 : 1 Sample-3 : 0 Sample-3 : 2 Sample-3 : 2 Sample-3 : 1 Sample-3 : 1 . . .
I can understand that the order in which threads are executed may differ and therefore the counter does not increase with rounding. However, I donβt understand why all ID displayed as Sample-3 , while the execution explicitly occurs independently of each other.
Arent different objects used with different threads?
Danish khan
source share