Thread Question - When do they die?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jehugaleahsa@gmail.com

    Thread Question - When do they die?

    I have some code that looks like this:

    int[] customerIds = { 1, 2, 3, 4, 5, 6, 7, 8 };
    List<Threadthre ads = new List<Threads>() ;
    foreach (int customerId in customerIds)
    {
    Thread thread = new Thread(delegate ()
    {
    // do calculation with customerId
    });
    threads.Add(thr ead);
    thread.Start();
    }
    foreach (Thread thread in threads)
    {
    thread.Join();
    }

    First, when I run this code, it appears as though 8 is executed
    multiple times. My guess is that the thread continues on after the
    delegate finishes, and since MoveNext() on the List<intjust returns
    the last item over an over, we see 8 multiple times. Is that accurate?

    Furthermore, something seems wrong about storing threads in a
    List<Threadand then joining. Is there a better way to Join these
    theads without keeping a reference to them around?

    Thanks,
    Travis
  • jehugaleahsa@gmail.com

    #2
    Re: Thread Question - When do they die?

    First, when I run this code, it appears as though 8 is executed
    multiple times. My guess is that the thread continues on after the
    delegate finishes, and since MoveNext() on the List<intjust returns
    the last item over an over, we see 8 multiple times. Is that accurate?
    I see I was totally wrong. Is this caused by me using anonymous
    methods?

    Comment

    Working...