Johnathan Enslin Johnathan Enslin - 2 months ago 7
C# Question

C# Task not completing (no results in command prompt)

using System;
using System.Threading.Tasks;

namespace _1._8_Starting_A_New_Task
{
public static class Program
{
public static void Main()
{
Task t = new Task(() =>
{
for (int x = 0; x < 100; x++)
{
Console.Write('*');
}
});

t.Wait();
}

}
}



  • This application compiles and runs displaying a blank screen (waiting on the task to complete)

  • The task stays in a waiting state

  • No output is displayed/written to console

  • Why not?

  • Application stays in "wait" state permanently

  • Why?

  • Goal of code: Start a new task, wait for task to complete, exit application


Answer

Because you never start the Task. Using the Task constructor requires you to call Task.Start on the returned task. This is why it's recommended to use Task.Run instead, which returns a "Hot task" (a task which has started):

The documentation:

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task.Run(Action) or TaskFactory.StartNew(Action) method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

So the code should be:

public static void Main()
{
    Task t = Task.Run(() =>
    {
        for (int x = 0; x < 100; x++)
        {
            Console.Write('*');
        }
    });

    t.Wait();
}