Search code examples
c#.netconsole-applicationtask-parallel-library

How to use the Task.ContinueWith, to avoid closing the console window?


I encountered a simple problem when trying to test TPL. I would like to get numbers (from 1 to 1000) for example in the console window.

This is the code that I have:

class Program
{
    static void Main(string[] args)
    {
        Task.Factory.StartNew(Calculate).ContinueWith(task =>
        {
            Task.WaitAll();
            Console.ReadKey();
        });
    }

    private static void Calculate()
    {
        for (var number = 0; number < 1000; number++)
        {
            Console.WriteLine(number);
        }
    }
}

The problem is that window just closes and it doesn't show anything. I know that I messed something up in ContinueWith method. I suspect that ContinueWith is not executed (because window just closes without my input) but I don't know why.

Any suggestions are helpful (Tried reading MSDN but to no avail). Thanks in advance.


Solution

  • Continuation runs asynchronously. If you do a little test:

    public static void Main(string[] args)
    {
        Task.Factory.StartNew(Calculate).ContinueWith(task =>
                                                          {
                                                              Console.WriteLine("Finished!");
                                                          });
        Console.WriteLine("Press ENTER to close...");
        Console.ReadLine();
    }
    

    You'll see

    Press ENTER to close...

    1

    2

    3

    ...

    999

    Finished!

    Because the continuation doesn't block.

    If you want to block the main execution thread to wait for the task, you can do:

    var task = Task.Factory.StartNew(Calculate);
    task.Wait();
    

    And it will block on Wait.