Solved

Threadpool arguments have strange values

Posted on 2012-04-04
3
311 Views
Last Modified: 2012-04-05
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());                
            }
        }
0
Comment
Question by:Alw1n
  • 2
3 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 37809258
I just happened to read about this very scenario--though I cannot remember where, for the life of me  : \

Your problem is that the compiler will create a closure around the variable "i" since you passed it to your lambda. I don't know all the ins and outs of closures, but it basically means your lambda will see all of the updates to "i" that the for loop makes (depending on the timing of each thread). To rectify, introduce a new local variable and assign i's value to that. Then pass this new variable to the lambda.

e.g.

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

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

Open in new window

0
 

Author Closing Comment

by:Alw1n
ID: 37809673
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?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37810405
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.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now