【发布时间】: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