Solved

Threadpool arguments have strange values

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

Title # Comments Views Activity
Object Oriented Programming, C#, referencing, scoping. 13 69
location of a form 2 25
TimeZone, day light savings, Sql server, asp.net 6 37
how to just get time from a date 6 32
A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

839 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