Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8703539
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T02:53:24+00:00 2026-06-13T02:53:24+00:00

In the question below, I found this neat trick for calling QueueUserWorkItem in a

  • 0

In the question below, I found this neat trick for calling QueueUserWorkItem in a type safe way, where you pass a delegate instead of WaitCallBack and an object. However, it doesn’t work the way one would expect.

What's the difference between QueueUserWorkItem() and BeginInvoke(), for performing an asynchronous activity with no return types needed

Here’s some sample code and output that demonstrates the issue.

for (int i = 0; i < 10; ++i)
{
    // doesn't work - somehow DoWork is invoked with i=10 each time!!!
    ThreadPool.QueueUserWorkItem(delegate { DoWork("closure", i); });

    // not type safe, but it works
    ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), Tuple.Create("    WCB", i));
}

void DoWork(string s, int i)
{
    Console.WriteLine("{0} - i:{1}", s, i);
}

void DoWork(object state)
{
    var t = (Tuple<string, int>)state;
    DoWork(t.Item1, t.Item2);
}

and here is the output:

closure - i:10
    WCB - i:0
closure - i:10
    WCB - i:2
    WCB - i:3
closure - i:10
    WCB - i:4
closure - i:10
    WCB - i:5
closure - i:10
    WCB - i:6
closure - i:10
    WCB - i:7
closure - i:10
    WCB - i:8
closure - i:10
    WCB - i:9
    WCB - i:1
closure - i:10

Note that when using the closure to call QueueUserWorkitem, i=10 for ever call, but when using the WaitCallBack you get the correct values, 0-9.

So my questions are:

  1. Why isn’t the correct value of i passed when using the closure/delegate way of doing it?
  2. How on earth does i ever get to be 10? In the loop, it only ever had values 0-9 right?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T02:53:26+00:00Added an answer on June 13, 2026 at 2:53 am

    The answers to both of your question are related to the scope of the closure when you create the anonymous method.

    When you do this:

    // Closure for anonymous function call begins here.
    for (int i = 0; i < 10; ++i)
    {
        // i is captured
        ThreadPool.QueueUserWorkItem(delegate { DoWork("closure", i); });
    }
    

    You’re capturing i across the entire loop. That means that you queue up your ten threads very quickly, and by the time they start, the closure has captured i to be 10.

    To get around this, you reduce the scope of the closure, by introducing a variable inside the loop, like so:

    for (int i = 0; i < 10; ++i)
    {
        // Closure extends to here.
        var copy = i;
    
        // **copy** is captured
        ThreadPool.QueueUserWorkItem(delegate { DoWork("closure", copy); });
    }
    

    Here, the closure doesn’t extend beyond the loop, but just to the value inside.

    That said, the second call to the QueueUserWorkItem produces the desired result because you’ve created the Tuple<T1, T2> at the time that the delegate is being queued up, the value is fixed at that point.

    Note that in C# 5.0, the behavior for foreach was changed because it happens so often (where the closure closes over the loop) and causes a number of people a lot of headaches (but not for like you are using).

    If you want to take advantage of that fact, you can call the Range method on the Enumerable class to use foreach:

    foreach (int i in Enumerable.Range(0, 10))
    {
        // Closure for anonymous function call begins here.
        ThreadPool.QueueUserWorkItem(delegate { DoWork("closure", i); });
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've found this question on StackOverflow Adding div below images in colorbox But it
I have two classes and two pages found below: My question is how do
I've searched for a potential answer to my question below, and have not found
OK I found this question: How do I delete a matching line, the line
I found this question Can't use relative paths with areas in ASP.NET MVC 2
I found (from this question - Hide div if screen is smaller than a
Based on some other code I found from this site (This Question here -
I am having doubts on when an autoreleased object. WHen I found this question
(See question below for more context): Are there any situations in which <machineKey validationKey=AutoGenerate,IsolateApps
The question below is not really a programming question, but more of how can

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.