Click here to Skip to main content
16,013,605 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi... All, I want to ask. I have the following code :

internal static class Program
{    
    private static Int32 number = 0;        
    private static Boolean IsComplete = false; 
    private static void Main()
    {        
        Action<Int32> action = arg =>
        {
            for (Int32 i = 0; i < arg; i++)
            {                
                Thread.Sleep(700);
                Console.WriteLine("Result : " + (number += i));
            }                        
        };
 
        action.BeginInvoke(5,
            arg =>
            {                
                Console.WriteLine("action complete, result = {0}", (Int32)arg.AsyncState);                
                IsComplete = true;
            }, 
            number);//if number changed to 10, then "result = 10" printed 
        while (!IsComplete)
        {
            Thread.Sleep(500);
            Console.WriteLine("Main is doing more...");
        }
 
        Console.ReadLine();
    }
}


Why, when action has finished and it's callback method get called always
printed "action complete, result = 0"(number isn't passed-in to callback method).
But, when I pass-in 10, then it will passed-in to the call back method ?
Posted
Updated 8-Jun-11 2:45am
v8

1 solution

It works fine!

All you have to do is remember when things happen.

Action<int32> action = arg =>
{
    for (Int32 i = 0; i < arg; i++)
    {
        Thread.Sleep(700);
        Console.WriteLine("Result : " + (number += i));
    }
};</int32>
Sets up the delegate. Nothing gets executed yet.
action.BeginInvoke(5,
    arg =>
    {
        Console.WriteLine("action complete, result = {0}", (Int32)arg.AsyncState);
        IsComplete = true;
    },
    number);//if number changed to 10, then "result = 10" printed
Evaluates all parameters, then starts the invoke. The parameters evaluate to:
A constant: 5
An anonymous delegate.
The current value of Number: 0
The thread is then created, and starts. But, the anonymous delegate that is executed when it finishes already has it's parameters ready: 0
while (!IsComplete)
{
    Thread.Sleep(500);
    Console.WriteLine("Main is doing more...");
}
Waits for the invoked thread to complete.

So, when the thread complete, it prints zero, not the final value of number.
When you change "number" to "10" the parameter evaluation is of a constant value.

To prove it, make the initial value of number -6 and see what happens!
 
Share this answer
 
Comments
adaapanya 10-Apr-11 3:38am    
Thanks man
OriginalGriff 10-Apr-11 3:42am    
Welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900