Link to home
Start Free TrialLog in
Avatar of Alw1n
Alw1n

asked on

Threadpool arguments have strange values

Hi,
I cannot figure out what I am doing wrong in my code below, I would expect a print of "1" then "2" but instead I get "3" and "3", please help.


        private void bTest_Click(object sender, EventArgs e)
        {

            for (int i = 1; i <= 2; i++)
            {
      XX xx = new XX();

                ThreadPool.QueueUserWorkItem(o =>
                    {
                        try
                        {
                            xx.SendMsg(i);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    });                                
            }
        }

        public class XX
        {
            public void SendMsg(object n)
            {
                System.Diagnostics.Debug.Print( n.ToString());                
            }
        }
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Alw1n
Alw1n

ASKER

Good answer!  I don't know about 'Closures' & will need to check that out. Out of interest, this situation only ocurrs when using lambda, the code below works fine:

ThreadPool.QueueUserWorkItem(new WaitCallback( xx.SendMsg), i);

The only benefit I see to using lambda is that you can use try/catch blocks etc. around the call, would there be any other reason to use lambda vs the original way?
You can use try/catch within a regular function as well--you just don't see them until you actually navigate to that function (within the IDE). If there is a benefit to using one over the other, I don't know what it would be. To me it seems a matter of preference. Either way you are passing a function.