当我使用任务秒表时,将显示经过的时间,但是当我使用线程时,它将不会显示.这是为什么?

Sui*_* Go 0 c# multithreading task task-parallel-library

我很困惑,为什么当我使用任务秒表的时间会显示但是当我使用线程时它不会.我的代码出了什么问题?我错过了什么吗?

static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        //if I used this sw.Elapsed will display
        //Task t1 = Task.Factory.StartNew(runTask1);
        //Task t2 = Task.Factory.StartNew(runTask2);
        //Task.WaitAll(t1, t2);

        //if I used this sw.Elapsed will not display
        //Thread t1 = new Thread(runTask1);
        //Thread t2 = new Thread(runTask2);
        //t1.Start();
        //t2.Start();

        sw.Stop();

        Console.WriteLine(sw.Elapsed);

        Console.ReadLine();
    }

    public static void runTask1()
    {
        for (int x = 1; x <= 5000; x++)
        {
            Console.WriteLine("Run task tester 1");
        }
    }
    public static void runTask2()
    {
        for (int x = 1; x <= 5000; x++)
        {
            Console.WriteLine("Run task tester 2");
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dam*_*Arh 6

当您使用任务时,等待他们完成工作,然后停止秒表并显示时间.当您使用线程时,您不会在显示结果之前等待它们完成,因此它将打印在线程文本的顶部.

你想等待线程完成:

static void Main(string[] args)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();

    // add Thread.Join at the end
    Thread t1 = new Thread(runTask1);
    Thread t2 = new Thread(runTask2);
    t1.Start();
    t2.Start();
    t1.Join();
    t2.Join();

    sw.Stop();

    Console.WriteLine(sw.Elapsed);

    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)