C# 任务未完成(命令提示符中无结果)

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

    }
}

因为你从来没有启动过Task。使用 Task constructor requires you to call Task.Start on the returned task. This is why it's recommended to use Task.Run 代替,其中 returns 一个 "Hot task" (已经开始的任务):

文档:

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.

所以代码应该是:

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

    t.Wait();
}