Strange behaviour of Console.ReadKey() with multithreading

前端 未结 3 548
孤街浪徒
孤街浪徒 2020-11-27 22:41

I\'m getting a weird problem when using Console.ReadKey() in a multithreaded program.

My question is: Why is this happening? Is it a bug, or is it becau

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 23:12

    It is confirmed internal bug in .NET 4.5. It has been reported for example here: https://connect.microsoft.com/VisualStudio/feedback/details/778650/undocumented-locking-behaviour-in-system-console

    This worked in .NET 3.5 and .NET 4.

    More info: http://blogs.microsoft.co.il/blogs/dorony/archive/2012/09/12/console-readkey-net-4-5-changes-may-deadlock-your-system.aspx

    You can use simple workaround to init internal structures and avoid blocking. Just add this to the beggining (from @renestein):

    Console.Error.WriteLine(); 
    Console.WriteLine(); 
    

提交回复
热议问题