Console.WriteLine(“”); gets stuck

后端 未结 3 1116
故里飘歌
故里飘歌 2021-01-08 00:25

Sometimes when I execute the above statement, the program freezes in a console application. If I break, I can\'t move to the next line. Do I need to reset a buffer or someth

3条回答
  •  清酒与你
    2021-01-08 01:03

    Using the System.Threading.Tasks.Dataflow nuget package, you can use a buffer to help with not locking the application in the event the user selects text on the console window

        private static BufferBlock _buffer = new BufferBlock();
        private static Task _consumer;
        private static CancellationTokenSource _cts;
    
        public static void Main(string[] args)
        {
            _buffer = new BufferBlock();
            _cts = new CancellationTokenSource();
            _consumer = ConsumeAsync(_buffer, _cts.Token);
    
            for (int i = 0; i < 100000; i++)
            {
                WriteToConsole(i.ToString());
            }
    
            Console.ReadLine();
        }
    
        private static void WriteToConsole(string message)
        {
            SendToBuffer(_buffer, message);
        }
    
        private static void SendToBuffer(ITargetBlock target, string message)
        {
            target.Post(message);
        }
    
        private static async Task ConsumeAsync(IReceivableSourceBlock source, CancellationToken cancellationToken)
        {
            while (await source.OutputAvailableAsync(cancellationToken))
            {
                var message = await source.ReceiveAsync();
    
                Console.WriteLine(message);
            }
        }
    

    This means writing to console won't block at all, so it's probably not useful in a lot of scenarios. In my case I just needed to spit out logging info

提交回复
热议问题