none
Simple Worker Thread in WCF - Why index of a loop goes wrong ? RRS feed

  • Question

  • I have a very simple WCF service,  : 

    [service contract]

    public class Service1 : IService1
        {

            List<int> m_list = new List<int>();

            public Service1()
            {
                for (int i = 0; i < 10; i++)
                {
                    m_list.Add(i);
                }
            }


    [OperationContract]
            public string GetData(int value)
            {
                for (int i = 0; i < 4; i++)
                {
                    Thread t = new Thread(() => simpleThread(i));
                    t.Start();
                }

            }

            void  simpleThread(int i_in) 
            {
                Trace.WriteLine(m_list[i_in].ToString());
            }

    }

    The code stores 0,1,2,3 as values inside m_list. So m_list[0] is 0, [1] is 1 .. [3] is 3.

    And when we print it through "SimpleThread(int i)" Thread function, In the log it's supposed to be 0,1,2,3 but it's always like  2,2,3 or something weird. And the index passed in itself is wrong. It never passes 0,1.  And sometimes it prints...

    4 : 4
    4 : 4
    4 : 4
    4 : 4


    And the problem is random.  I'm missing something very fundamental with threading on WCF. Any help please?

    I would like to get it :

    0 : 0

    1 : 1

    2 : 2

    3 : 3


    hibrise



    Wednesday, March 13, 2013 5:01 AM

Answers

  • Ciao Hibrise.live.in,

    You wrote on 13/03/2013 :

    Thread t = new Thread(() => simpleThread(i));
     t.Start();

    And the problem is random.  I'm missing something very fundamental with threading on WCF. Any help please?

    seems to e a closure problem, the "Action" is late bound to the thread, thus at the time is bound the value of i is changed.
    Pass "i" to the new Thread as "state", there should be an overload for that, and retrieve the state in the delegate.

    .m



    blog @ //milestone.topics.it
    Wednesday, March 13, 2013 6:05 AM
  • ParameterizedThread start solves the problem.

    thanks


    hibrise

    Wednesday, March 20, 2013 9:14 AM

All replies

  • Ciao Hibrise.live.in,

    You wrote on 13/03/2013 :

    Thread t = new Thread(() => simpleThread(i));
     t.Start();

    And the problem is random.  I'm missing something very fundamental with threading on WCF. Any help please?

    seems to e a closure problem, the "Action" is late bound to the thread, thus at the time is bound the value of i is changed.
    Pass "i" to the new Thread as "state", there should be an overload for that, and retrieve the state in the delegate.

    .m



    blog @ //milestone.topics.it
    Wednesday, March 13, 2013 6:05 AM
  • ParameterizedThread start solves the problem.

    thanks


    hibrise

    Wednesday, March 20, 2013 9:14 AM