Home > Net >  Why output on console freeze after first output?
Why output on console freeze after first output?

Time:09-17

Here I have simple code written in C#.

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Reactive.Subjects;

namespace ReactiveProgramming
{
    class Program
    {

        static void Main(string[] args)
        {
            var generateSeq = new GenerateSequence();
            Console.WriteLine("Hello World!");

            generateSeq.Sequence.Subscribe(val =>
            {
                Console.WriteLine(val);

                // it works if I remove below two lines ...
                Console.SetCursorPosition(0, Console.CursorTop - 1);   
                Console.Write("\r"   new string(' ', Console.WindowWidth)   "\r");
            });

            generateSeq.Run();
        }
    }

    class GenerateSequence
    {
        public Subject<int> Sequence = new Subject<int>();

        public void Run(int runTimes = 10)
        {
            ConsoleKeyInfo cki;

            Task.Run(() => runForTimes(10));

            do
            {
                cki = Console.ReadKey();
            } while (cki.Key != ConsoleKey.Escape);
        }

        public void runForTimes(int runTimes = 10)
        {
            for (var i = 0; i < 10; i  )
            {
                Sequence.OnNext(i);
                Thread.Sleep(1000);
            }
        }
    }
}

But instead of printing sequence on top of each other, it just freeze the output after first emit.

And tested in Linux too ... same output.

Screenshot

If I remote these lines Console.SetCursorPosition and Console.Write("\r" new string(' ', Console.WindowWidth) "\r") from subscribe ... it works and print all numbers on screen one after another but I want to print on top of each other ...

But if I change my Main function like this:

    static void Main(string[] args)
    {
        var generateSeq = new GenerateSequence();
        Console.WriteLine("Hello World!");

        generateSeq.Sequence.Subscribe(val =>
        {
            Console.WriteLine(val);
            // Console.SetCursorPosition(0, Console.CursorTop - 1);
            // Console.Write("\r"   new string(' ', Console.WindowWidth)   "\r");
        });

        generateSeq.Run();
    }

Where I have commented those two lines ... output is as follows ...

Screenshot

But instead of output in sequence like second image, I want to print the output at the same position. Just over write the new output over the old one

Note: I am running it on Macbook Pro (Big Sur), it happens with .net core 3.1 or .net 5.0 and using iTerm as console emulator

CodePudding user response:

If I were writing this, I'd go with this implementation:

    static async Task Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        IObservable<System.ConsoleKeyInfo> keys =
            Observable
                .Start(() => Console.ReadKey());

        await
            Observable
                .Interval(TimeSpan.FromSeconds(1.0))
                .Take(10)
                .TakeUntil(keys)
                .Do(x =>
                {
                    Console.WriteLine(x);
                    Console.SetCursorPosition(0, Console.CursorTop - 1);
                },
                () => Console.SetCursorPosition(0, Console.CursorTop   1));

        Console.WriteLine("Bye World!");
    }

Wherever possible you should avoid using subjects.

CodePudding user response:

SetCursorPosition works perfectly fine when not called from another thread. you can use an asynchronous approach to solve the problem instead of using Task.Run

  class Program
    {
        static void Main(string[] args)
        {
            var generateSeq = new GenerateSequence();
            Console.WriteLine("Hello World!");

            generateSeq.Sequence.Subscribe(val =>
            {
                Console.WriteLine(val);
                // move cursor back to previous line
                Console.SetCursorPosition(0 ,Console.CursorTop - 1);
            });
            
            // start background operation
            generateSeq.Run();
        }
    }
    
    class GenerateSequence
    {
        public readonly Subject<int> Sequence = new();

        public void Run(int runTimes = 10)
        {
            ConsoleKeyInfo cki;

            // create a cancelation token, because if the user presses
            // Escape key we don't need to run our background task 
            // anymore and the task should be stopped.
            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            // we can not use await keyword here because we need to 
            // listen to ReadKey functions in case the user wants to 
            // stop the execution. without the await, task will run in 
            // the background asynchronously
            var task = RunForTimes(runTimes,token);

            // wait for the Escape key to cancel the execution or stop it 
            // if it's already running
            do
            {
                cki = Console.ReadKey();
            } while (cki.Key != ConsoleKey.Escape && !task.IsCompleted);

            // cancel the background task if it's not compeleted.
            if (!task.IsCompleted)
                tokenSource.Cancel();    
            
            // Revert CursorPosition to the original state
            Console.SetCursorPosition(0, Console.CursorTop   1); 

            Console.WriteLine("Execution ends");
        }

        // we use an async task instead of a void to run our background 
        // job Asynchronously.
        // the main difference is, we should not use a separate thread 
        // because we need to be on the main thread to safely access the Console (to read or write)
        private async Task RunForTimes(int runTimes, CancellationToken token)
        {
            for (var i = 0; i < runTimes; i  )
            {
                // cancel the operation if it is requested
                if (token.IsCancellationRequested) return;
                Sequence.OnNext(i);
                await Task.Delay(1000, token);
            }
        }
    }

enter image description here

  • Related