在下面的代码中,我试图在线程执行完成后显示秒表的经过时间,但我无法这样做
秒表的经过时间总是显示为0,无论我是否使用thread.isalive
如何在执行后台线程后显示秒表的经过时间?
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();
}
}
答案 0 :(得分:1)
你的假设是错误的:
这是因为您的Thread执行是异步的。你告诉你的程序启动线程(它将至少执行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));