C#异步委托(delegate),线程调度

标签 c# .net multithreading asynchronous

我对线程完全陌生,并试图了解最基础的知识。我有这段带有异步委托(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...

output

据我了解,输出顺序应该是不确定的。在这种情况下是。线程队列是如何处理的?我错过了什么?请解释一下

最佳答案

当您在 var input = Console.ReadLine(); 上等待用户输入时,您基本上是在锁定您的线程。第一个等待输入并在收到时打印它。另一个线程在确切的时间已经要求输入并等待它。所以你每一个都得到一行。

如果您删除 ReadLine 并改用此行:

var input = "Hamster";

你会得到你想要的结果:

enter image description here

关于C#异步委托(delegate),线程调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21351625/

相关文章:

android - 开发基于 Windows 的手机的移动应用程序

.net - 什么是 VB.NET 等同于这种创建实例的方式?

c# - 在当前具有焦点的任何元素周围放置一个鲜红色框的可重用方法?

c# - 比较可为空的 DateTimeOffset 变量的最佳方法?

c# - 这个 LINQ 查询有什么作用?

c# - 在 ReflectionOnlyLoad 期间忽略缺失的依赖项

java - 这里是否存在潜在的 ConcurrentModificationException?我的解决方案正确吗?

android - 如何使用通知和等待

c++ - 在 pthreads 中指定线程堆栈大小

c# - 网络作业 : Library not found