我目前正在阅读有关线程的this excellent article并阅读以下文本:



我想测试一下,下面是我的测试代码:

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运行的函数:
static void SetPoints()
{
    while(true)
    {
        s += ".";
    }
}

static void SetNewLines()
{
    while(true)
    {
        s += "\n";
        Thread.Sleep(0);
    }
}

如果我正确理解Thread.Sleep(0),输出应该是这样的:
............        |
..............      |
................    | <- End of console
..........          |
.............       |
...............     |

但是我得到这个作为输出:
....................|
....................|
....                |
                    |
                    |
....................|
....................|
.................   |
                    |

看到许多程序员强烈推荐这篇文章开头提到的文章,我只能假设我对Thread.Sleep(0)的理解是错误的。因此,如果有人可以澄清,我将很有义务。

最佳答案

thread.sleep(0)的作用是使CPU释放以处理其他线程,但这并不意味着另一个线程不能成为当前线程。如果您试图将上下文发送到另一个线程,请尝试使用某种信号。

关于c# - Thread.Sleep(0)不能按说明工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17365502/

10-17 01:42