Solved

Threadpool arguments have strange values

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
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…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

808 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