0

我很困惑为什么当我使用任务时会显示秒表的时间,而当我使用线程时却不会。我的代码有什么问题?我错过了什么吗?

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");
        }
    }
4

1 回答 1

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();
}
于 2012-11-17T05:48:20.773 回答