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();
}
}
}
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)
orTaskFactory.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();
}