D
d225563
I read an article that had a really elegant solution to pass parameters
to a thread by using an anonymous method as your ThreadStart. It
seemed pretty slick and even worked when I tried it. However, with
some more playing around, I got some really strange results. Using the
code below, sometimes my output is 2 and 3. Sometimes, it's 3 and 3.
However, it's never been 1 and 2 which is what I would expect. Can
anybody set me straight on why I'm getting the unexpected results? My
suspicion is that somehow my integer is getting passed by reference
rather than value, but I'd like someone else to corroborate that before
I go on believing it. (Note: I know about ParameterizedThreadStart.
I'm just trying to use this example to understand anonymous methods a
little better.)
namespace AnonymousConfusion
{
class Program
{
static void Main(string[] args)
{
int i = 1;
ThreadStart ts1 = delegate { WorkThread(i); };
Thread t1 = new Thread(ts1);
// i should be 1 when i'm starting my thread, right?
t1.Start();
i++;
ThreadStart ts2 = delegate { WorkThread(i); };
Thread t2 = new Thread(ts2);
// i should 2 when i'm starting my thread, right?
t2.Start();
i++;
t1.Join();
t2.Join();
// why am i getting 2 and 3 or sometimes 3 and 3 for
output?
Console.WriteLine("Done");
Console.ReadLine();
}
static void WorkThread(int i)
{
Console.WriteLine(i.ToString());
}
}
}
to a thread by using an anonymous method as your ThreadStart. It
seemed pretty slick and even worked when I tried it. However, with
some more playing around, I got some really strange results. Using the
code below, sometimes my output is 2 and 3. Sometimes, it's 3 and 3.
However, it's never been 1 and 2 which is what I would expect. Can
anybody set me straight on why I'm getting the unexpected results? My
suspicion is that somehow my integer is getting passed by reference
rather than value, but I'd like someone else to corroborate that before
I go on believing it. (Note: I know about ParameterizedThreadStart.
I'm just trying to use this example to understand anonymous methods a
little better.)
namespace AnonymousConfusion
{
class Program
{
static void Main(string[] args)
{
int i = 1;
ThreadStart ts1 = delegate { WorkThread(i); };
Thread t1 = new Thread(ts1);
// i should be 1 when i'm starting my thread, right?
t1.Start();
i++;
ThreadStart ts2 = delegate { WorkThread(i); };
Thread t2 = new Thread(ts2);
// i should 2 when i'm starting my thread, right?
t2.Start();
i++;
t1.Join();
t2.Join();
// why am i getting 2 and 3 or sometimes 3 and 3 for
output?
Console.WriteLine("Done");
Console.ReadLine();
}
static void WorkThread(int i)
{
Console.WriteLine(i.ToString());
}
}
}