Note that there are some explanatory texts on larger screens.

plurals
  1. POQueueUserWorkItem with delegate does not work, but WaitCallBack does work
    text
    copied!<p>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.</p> <p><a href="https://stackoverflow.com/questions/532791/whats-the-difference-between-queueuserworkitem-and-begininvoke-for-perform">What&#39;s the difference between QueueUserWorkItem() and BeginInvoke(), for performing an asynchronous activity with no return types needed</a></p> <p>Here's some sample code and output that demonstrates the issue.</p> <pre><code>for (int i = 0; i &lt; 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&lt;string, int&gt;)state; DoWork(t.Item1, t.Item2); } </code></pre> <p>and here is the output:</p> <pre><code>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 </code></pre> <p>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. </p> <p>So my questions are:</p> <ol> <li>Why isn't the correct value of i passed when using the closure/delegate way of doing it? </li> <li>How on earth does i ever get to be 10? In the loop, it only ever had values 0-9 right?</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload