【问题标题】:Stopwatch Elapsed time after thread execution秒表 线程执行后经过的时间
【发布时间】:2017-10-03 08:29:04
【问题描述】:

在下面的代码中,我试图在线程执行完成后显示秒表的经过时间,但我无法这样做

无论我是否使用 thread.isalive,秒表的经过时间总是显示为 0

如何在后台线程执行后显示秒表经过的时间?

class Program
{
    static void myfunction()
    {
        Console.WriteLine("hi");
        Thread.Sleep(2000);
        Console.WriteLine("hi after 2 sec");
    }

    static void Main()
    {
        // create a new stopwatch and start it
        Stopwatch s = new Stopwatch();
        s.Start();  

        // make a new thread and start thread execution   
        Thread t = new Thread(myfunction);
        t.Start();

        // I m assuming that the thread t is dead once myfunction is completed

        // display elapsed time when thread has finished work and is dead 
        if (!t.IsAlive)   
           s.Stop();
            Console.WriteLine("Time elapsed: {0}", s.Elapsed.Seconds.ToString());

        Console.ReadKey();
    }
}

【问题讨论】:

    标签: stopwatch


    【解决方案1】:

    你的假设是错误的:

    这是因为您的线程执行是异步的。您告诉您的程序启动线程(将至少执行 2 秒),然后主线程继续执行您的 if 语句,这是错误的(线程仍在后台运行)。

    解决这个问题的一种方法是将秒表传递给myfunction

    static void myfunction(Stopwatch s)
    {
        Console.WriteLine("hi");
        Thread.Sleep(2000);
        Console.WriteLine("hi after 2 sec");
        Console.WriteLine("Time elapsed: {0}", s.Elapsed.Seconds.ToString());
    }
    

    然后在Main 中将您的线程初始化替换为:

    Thread t = new Thread(() => myfunction(s));
    

    【讨论】:

    • 感谢您快速准确的回复:)
    猜你喜欢
    • 2013-05-04
    • 2020-12-22
    • 2020-03-12
    • 1970-01-01
    • 2011-07-06
    • 2020-04-29
    • 2013-04-01
    • 1970-01-01
    相关资源
    最近更新 更多