As far as I can see, this is completely non-deterministic. You could get values all the way from ten zeroes being written all the way up to ten tens and all incrementing variations in between.
The why is that you do not have any sort of synchronized and/or serialized access to your numCounter
variable. The threads will read it only when the thread is executing, which could happen at any time, based on any number of environmental conditions.
The quick way to get all numbers, with no repeats would be thus:
public int numCounter;
private void button2_Click(object sender, EventArgs e)
{
for (numCounter = 0; numCounter < 10; numCounter++)
{
Thread myThread = new Thread(myMethod);
myThread.Start(numCounter);
}
}
public void myMethod(object numCounter)
{
Console.WriteLine(numCounter);
}
The main downsides here are 1) the signature of myMethod
has to change, 2) boxing occurs when converting numCounter
from an int
to an object
and 3) this still doesn't guarantee the output is in the order 0..10 that may be expected.
Here's a slightly different version which uses a delegate
and BeginInvoke
/EndInvoke
(the way I like doing threading). It eliminates downside #2 from above, but still keeps #1 and #3:
public int numCounter;
private delegate void MyMethodDelegate(int numCounter);
private void button2_Click(object sender, EventArgs e)
{
for (numCounter = 0; numCounter < 10; numCounter++)
{
MyMethodDelegate myDelegate = new MyMethodDelegate(myMethod);
myDelegate.BeginInvoke(numCounter, myMethodDone, myDelegate);
}
}
public void myMethod(int numCounter)
{
Console.WriteLine(numCounter);
}
public void myMethodDone(IAsyncResult result)
{
MyMethodDelegate myDelegate = result.AsyncState as MyMethodDelegate;
if (myDelegate != null)
{
myDelegate.EndInvoke(result);
}
}