我目前正在读穿线这个优秀的文章并阅读下面的文字:
I am currently reading this excellent article on threading and read the following text:
的Thread.Sleep(0)放弃立即线程的当前时间片,自愿交出CPU给其他线程。
Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads.
我想测试这一点,下面是我的测试代码:
I wanted to test this and below is my test code:
static string s = ""; static void Main(string[] args) { //Create two threads that append string s Thread threadPoints = new Thread(SetPoints); Thread threadNewLines = new Thread(SetNewLines); //Start threads threadPoints.Start(); threadNewLines.Start(); //Wait one second for threads to manipulate string s Thread.Sleep(1000); //Threads have an infinite loop so we have to close them forcefully. threadPoints.Abort(); threadNewLines.Abort(); //Print string s and wait for user-input Console.WriteLine(s); Console.ReadKey(); }这threadPoints和threadNewLines运行的功能:
The functions that threadPoints and threadNewLines run:
static void SetPoints() { while(true) { s += "."; } } static void SetNewLines() { while(true) { s += "\n"; Thread.Sleep(0); } }如果我(0)正确认识了Thread.Sleep,输出应该是这样的:
If I understand Thread.Sleep(0) correctly, the output should be something like this:
............ | .............. | ................ | <- End of console .......... | ............. | ............... |
不过,我得到这个作为输出:
But I get this as output:
....................| ....................| .... | | | ....................| ....................| ................. | |看到作为文章的开头提到的文章深受许多程序员建议,我只能假设我的Thread.Sleep的理解(0)是错误的。所以,如果有人可以澄清一下,我会非常感激。
Seeing as the article mentioned in the beginning of the post is highly recommended by many programmers, I can only assume that my understanding of Thread.Sleep(0) is wrong. So if someone could clarify, I'd be much obliged.
推荐答案什么的Thread.Sleep(0)是释放CPU的以处理其他的线程,但是这并不意味着另一个线程不能当前之一。如果你想上下文发送到另一个线程,尝试使用某种信号。
What thread.sleep(0) is to free the cpu to handle other threads, but that doesn't mean that another thread couldn't be the current one. If you're trying to send the context to another thread, try to use some sort of signal.
更多推荐
Thread.sleep代码(0)所描述不起作用?
发布评论