Antony Thomas
Antony Thomas

Reputation: 3696

Assistance needed with Task.ContinueWith()

Maybe I am missing something petty (will remove post if that is the case). Can someone tell me what I am doing wrong with this .ContinueWith() ? I do not see the result printed in the screen.

public static void Main()
{
    Task<int> t = new Task<int>(() => { return Sum(5); });
    t.Start();
    t.Wait();
    t.ContinueWith((task) => { Console.WriteLine(task.Result); });
    //Console.WriteLine(t.Result); //this works

    Console.Read();
}

public static int Sum(int n)
{
    return 50;//stub result
}

Upvotes: 0

Views: 692

Answers (1)

Peter Ritchie
Peter Ritchie

Reputation: 35869

You're application is probably exiting before you continuation is run. If you put a breakpoint at end end of Main, you're stopping all threads while at that breakpoint and if the continuation hasn't run yet, it won't be allowed to run until you exit (and probably lose the output).

Try the following to see what happens:

public static void Main()
        {
            Task<int> t = new Task<int>(() => { return Sum(5); });
            t.Start();
            t.Wait();
            t.ContinueWith((task) => { Console.WriteLine(task.Result); });
            //Console.WriteLine(t.Result); //this works
            Console.ReadLine();
        }

Upvotes: 3

Related Questions