写使用Task.Run控制台()失败 [英] Writing to the console using Task.Run() fails
问题描述
我的一个同事发现了我们的代码是一个问题,过了好一会儿,追捕究竟发生了什么事,但它可以通过这个简单的例子来证明:
A colleague of mine found an issue with our code and it took a while to hunt down exactly what was happening, but it can be best demonstrated by this simple example:
// Fails
class Program
{
static void Main(string[] args)
{
Task.Run(() => Console.WriteLine("Hello World"));
Console.ReadKey();
}
}
// Works fine
class Program
{
static void Main(string[] args)
{
Console.Write(String.Empty);
Task.Run(() => Console.WriteLine("Hello World"));
Console.ReadKey();
}
}
这是从与此表示写入玩耍明确控制台从主线程的任何地方将允许后台线程写入控制台还,但我们正在努力理解为什么发生这种情况。谁能解释达到什么样的写作,从主线程控制台,第一个片断不?
It’s clear from playing around with this that writing to the console anywhere from the main thread will allow the background thread to write to the console also, but we are struggling to understand why this is happening. Can anyone explain what writing to the console from the main thread achieves that the first snippet does not?
推荐答案
我怀疑是到这是怎么回事。我所观察到的:
I have a suspicion as to what's going on. What I've observed:
- 如果你的任何的与启动<$ C $前控制台输出C> ReadKey ,它的罚款。这包括获取
Console.Out
,但不使用它 - 如果你把一个延迟,使
控制台.WriteLine
调用的启动的的Console.ReadKey
调用之前,它的罚款(你可以有多个的WriteLine
通话,而的ReadKey
正在等待
- If you do anything with the console's output before starting the
ReadKey
, it's fine. This includes fetchingConsole.Out
but not using it - If you put a delay in so that the
Console.WriteLine
call starts before theConsole.ReadKey
call, it's fine (and you can have multipleWriteLine
calls whileReadKey
is waiting
我怀疑是使用控制台的第一个操作可获取初始化锁(以避免它被初始化两次),而 ReadKey
方法保持锁定的的搁置,直到某个键读取。这当然会解释每次我跑这么远程序。
I suspect that the first operation to use the console acquires a lock for initialization (to avoid it being initialized twice) and that the ReadKey
method keeps hold of the lock until a key has been read. That would certainly explain every program I've run so far.
它们执行的操作假设的初始化是有趣的,但 - 读 Console.Out
修复的问题,而是从 Console.In
阅读没有按'T。
The operations which perform the hypothesized initialization are interesting though - reading Console.Out
"fixes" the issue, but reading from Console.In
doesn't.
我怀疑 ReadKey
初始化输出,因为该值仍回荡到控制台...但我不喜欢发誓吧。
I suspect that ReadKey
initializes the output because the value is still echoed to the console... but I wouldn't like to swear to it.
有趣的是,使用到Console.ReadLine()
而不是 Console.ReadKey()
不会导致摆在首位的问题。
Interestingly, using Console.ReadLine()
instead of Console.ReadKey()
doesn't cause the problem in the first place.
这篇关于写使用Task.Run控制台()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!