Solved

Threadpool arguments have strange values

Posted on 2012-04-04
3
309 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 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
This video discusses moving either the default database or any database to a new volume.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

772 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

14 Experts available now in Live!

Get 1:1 Help Now