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

2

27

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.

Remount answered 9/3, 2013 at 17:17 Comment(5)
Doesn't the StartNew create a new thread? because your main thread will just continue and will exit the application. shouldn't something be coded to at least hold the main thread until your background stuff is done?Expediency
I always thought that StartNew starts a task. Quote from MSDN: "Creates and starts a task." Link itself: msdn.microsoft.com/en-us/library/dd321439.aspxRemount
well it's part of TPL (task parallel library) so I'd guess it still relies on threads under water. Did you try to add a Console.ReadLine before your main method exits? Never tried anything with TPL but my best guess is that your application just exits and the rest of your implementation is fineExpediency
the doctor makes sense :). tried it here in a unit test. his solution worksExpediency
@Expediency is correct; the task is started asynchronously on a new thread, and the existence of that thread does not prevent control from falling off the end of Main and terminating the process.Oriflamme
S
37

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.

Simian answered 9/3, 2013 at 17:25 Comment(4)
djeeze they really made life easy with TPL... I should dive into this stuff too :). +1, quick and swift answer!Expediency
@Expediency Yes they did :) I really, really like the TPL, especially when paired with async & await in .NET 4.5. And then there's also TPL Dataflow...Cattalo
Thank you. Now I understand the basic idea behind this. :)Remount
Do I need to pay attention to anything additional when an error might occur?Reynaldoreynard
G
0

You must observe that, The Task class internally uses threads from the thread pool, that's mean this threads is a background threads and the background threads will terminate once the foreground thread terminated and the main method use main thread that's by default foreground thread, so u must add Console.ReadKey() to hold your program until the background threads finsih.

Grackle answered 7/7, 2024 at 5:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.