Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use Task.ContinueWith?

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.

like image 826
zmockus Avatar asked Mar 09 '13 17:03

zmockus


1 Answers

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.

like image 177
Patryk Ćwiek Avatar answered Oct 11 '22 12:10

Patryk Ćwiek