I get weird behavior ... when I iterate over dummyText Lista method ThreadTest, I get an exception from the exception range ( ArgumentOutOfRangeException), but if I delete the threads and I just print the text, then everything works fine.
This is my main method:
public static Object sync = new Object();
static void Main(string[] args)
{
ThreadTest();
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
This method throws an exception:
private static void ThreadTest()
{
Console.WriteLine("Running ThreadTest");
Console.WriteLine("Running ThreadTest");
List<String> dummyText = new List<string>()
{ "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten"};
for (int i = 0; i < dummyText.Count; i++)
{
Thread t = new Thread(() => PrintThreadName(dummyText[i]));
t.Name = ("Thread " + (i));
t.IsBackground = true;
t.Start();
}
}
private static void PrintThreadName(String text)
{
Random rand = new Random(DateTime.Now.Millisecond);
while (true)
{
lock (sync)
{
Console.WriteLine(Thread.CurrentThread.Name + " running " + text);
Thread.Sleep(1000+rand.Next(0,2000));
}
}
}
This throws an exception:
private static void ThreadTest()
{
Console.WriteLine("Running ThreadTest");
List<String> dummyText = new List<string>()
{ "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten"};
for (int i = 0; i < dummyText.Count; i++)
{
Console.WriteLine(dummyText[i]);
}
}
Does anyone know why this is happening?