以下代码演示了如何使用 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到这个输出-
In Main: Creating the child thread
Child thread starts
Child thread paused for <0> seconds
Child thread resumes
Run Code Online (Sandbox Code Playgroud)
但我期望的是:-
In Main: Creating the child thread
Child thread starts
Child thread paused for <5> seconds
Child thread resumes
Run Code Online (Sandbox Code Playgroud)
我该怎么做有什么建议吗?
小智 5
我认为这就是你错误的地方:
Console.WriteLine("Child Thread Paused for {0} seconds", (sleepfor/1000).ToString());
Run Code Online (Sandbox Code Playgroud)
您没有指定该值的{0}来源。
此外,您还需要从毫秒计算到秒,这就是为什么/1000