以下代码演示了如何使用sleep()方法使线程暂停一段特定的时间。
当我运行此代码时: -
class Program
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds");
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
我得到了这个输出 -
In Main: Creating the child thread
Child thread starts
Child thread paused for <0> seconds
Child thread resumes
但我的期望是: -
In Main: Creating the child thread
Child thread starts
Child thread paused for <5> seconds
Child thread resumes
我该怎么办呢?
答案 0 :(得分:4)
我认为这是你错误的地方:
Console.WriteLine("Child Thread Paused for {0} seconds", (sleepfor/1000).ToString());
您没有指定{0}
的值来自哪里。
您还需要从毫秒到秒计算,这就是为什么/1000
答案 1 :(得分:4)
如果您想查看Child thread passed for <5> seconds
,则需要准确打印。
以下是代码的问题行
Console.WriteLine("Child Thread Paused for {0} seconds");
这应该是
Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);
如您所知,您尚未在通话中指定参数{0}
。您可以参考Console.WriteLine()
请注意,Console.WriteLine
遵循String.Format
设置的格式规则。 format string rules can be seen here。
在较新的语法中,您不需要使用{0}
等占位符,但可以将表达式本身嵌入字符串中,称为Interpolated Strings
Console.WriteLine($"Child Thread Paused for <{sleepfor/1000}> seconds");
答案 2 :(得分:0)
Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);
或C#6方法:
Console.WriteLine($"Child Thread Paused for <{sleepfor/1000}> seconds");