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

时间:2012-11-17 05:42:24

标签: c# multithreading task-parallel-library task

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

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

1 个答案:

答案 0 :(得分: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();
}
相关问题