我对线程完全陌生,并试图了解最基础的知识。我有这段带有异步委托(delegate)调用的代码:
static void Main(string[] args)
{
Action<Thread, string> action = (mainThread, name) =>
{
Thread.CurrentThread.Name = name;
Thread.CurrentThread.IsBackground = false;
Console.WriteLine("Thread {0} starts", Thread.CurrentThread.Name);
while (true)
{
var input = Console.ReadLine();
Console.WriteLine("Thread {0} catches an input. User's input is: \"{1}\""
+"\nMain thread is alive = {2}",
Thread.CurrentThread.Name, input, mainThread.IsAlive);
}
};
action.BeginInvoke(Thread.CurrentThread,"First", null, null);
action.BeginInvoke(Thread.CurrentThread, "Second", null, null);
Thread.Sleep(2000);
}
无论我做什么,输出结果总是按以下顺序进行:First->Second->First->Second->First...
据我了解,输出顺序应该是不确定的。在这种情况下是。线程队列是如何处理的?我错过了什么?请解释一下
最佳答案
当您在 var input = Console.ReadLine();
上等待用户输入时,您基本上是在锁定您的线程。第一个等待输入并在收到时打印它。另一个线程在确切的时间已经要求输入并等待它。所以你每一个都得到一行。
如果您删除 ReadLine
并改用此行:
var input = "Hamster";
你会得到你想要的结果:
关于C#异步委托(delegate),线程调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21351625/