gpt4 book ai didi

c# - 了解多线程 C#

转载 作者:太空狗 更新时间:2023-10-29 17:56:59 24 4
gpt4 key购买 nike

我正在尝试了解多线程。我有一个示例,它从控制台应用程序中的 Main 方法运行两个线程。

new Thread(() =>
{
for (int x = 0; x < 10; x++)
{
Console.WriteLine("First :" + x);
}
}).Start();

new Thread(() =>
{
for (int x = 0; x < 10; x++)
{
Console.WriteLine("Second :" + x);
}
}).Start();

Console.ReadKey();

发生的事情是,我的控制台变黑了,上面没有任何内容,但是当我按下任意键时,它会显示正确的结果。为什么?

最佳答案

我们中的一些人(查看问题下的评论)看到新线程在 Console.ReadKey() 被调用之前完整执行,而其他人看到初始线程抢占新线程,等待通过 Console.ReadKey() 在执行新线程之前进行输入。

您有三个线程都在做自己的事情,都可能写入控制台并执行其他逻辑,并且您无法真正控制在任何特定时刻执行哪个线程。

从什么Eric说过,这种行为是预料之中的,并且您执行新线程的方式是可预见的不可预测的。 (在此处重新发布他的评论以防评论被清理)

Read my two fundamental rules again: (1) programs that try to do UI on two threads are broken, and (2) don't expect anything to behave normally. I have no expectation that the broken program given will produce any behaviour whatsoever. Moreover, I don't expect that the behaviour of a broken program will be consistent across multiple runs or across machines. I also don't expect that the behaviour will be inconsistent. Broken programs are broken; they are not required to be consistent or inconsistent in their bad behaviour.

有一个调用允许您阻塞初始(主)线程(恰好是调用线程),直到新线程完成执行,这就是 Thread.Join .您仍然无法控制两个新线程执行和写入控制台的顺序,但至少初始线程已暂停。

var threads = new Thread[] {
new Thread(() =>
{
for (int x = 0; x < 10000; x++)
{
Console.WriteLine("First :" + x);
}
}),
new Thread(() =>
{
for (int x = 0; x < 10000; x++)
{
Console.WriteLine("Second :" + x);
}
})
};

// start the threads
foreach (var t in threads)
t.Start();

// block the initial thread until the new threads are finished
foreach (var t in threads)
t.Join();

// Now the following line won't execute until both threads are done
Console.ReadKey();

关于c# - 了解多线程 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com