0

The code below returns the following output:

Semaphore sema = new Semaphore(5,5,"sema_1");
for (int i = 0; i < 10; i++)
{
    ThreadPool.QueueUserWorkItem(delegate(object state)
    {
        sema.WaitOne();
        Console.WriteLine(" = " + i);
        sema.Release();
    });
}

enter image description here

And just by adding the int j = i it completely changes the output to what I was expecting, which is the proper response reaching the limit of the Semaphore:

Semaphore sema = new Semaphore(5,5,"sema_1");
for (int i = 0; i < 10; i++)
{
    int j = i;
    ThreadPool.QueueUserWorkItem(delegate(object state)
    {
        sema.WaitOne();
        Console.WriteLine(" = " + j);
        sema.Release();
    });
}

enter image description here

RollRoll
  • 8,133
  • 20
  • 76
  • 135
  • I don't think it is duplicated – RollRoll Jun 29 '18 at 01:42
  • I don't get the behavior you're describing. Setting int j = i, does not cause i to be captured. Are you sure you aren't printing j? – MineR Jun 29 '18 at 02:13
  • it was a typo, I fixed it thanks – RollRoll Jun 29 '18 at 02:16
  • Yeah then it's a duplicate.... also see https://stackoverflow.com/questions/16264289/captured-closure-loop-variable-in-c-sharp-5-0 – MineR Jun 29 '18 at 02:19
  • Also see - https://stackoverflow.com/questions/25603965/why-do-some-c-sharp-lambda-expressions-compile-to-static-methods?rq=1, which shows how lambdas work. – MineR Jun 29 '18 at 02:26

0 Answers0