Escrenvendo on the Async Island

Asked

Viewed 177 times

1

How to make a Console program, while it processes some task it execute a writing on the console (like a counter) asynchronous? independent.

In other words, he will be writing independently of other processes. Something like:

ex:

        private static async Task EscreveConsole()
        {
            for (int i = 0; i < 100; i++)
            {
                Console.CursorTop = 4;
                Console.CursorLeft = 90;
                Console.Write("/"); System.Threading.Thread.Sleep(100);
                Console.Clear();
                Console.CursorTop = 4;
                Console.CursorLeft = 90;
                Console.Write("-"); System.Threading.Thread.Sleep(100);
                Console.CursorTop = 4;
                Console.CursorLeft = 90;
                Console.Write("\\"); System.Threading.Thread.Sleep(100);
                Console.CursorTop = 4;
                Console.CursorLeft = 90;
                Console.Write("|"); System.Threading.Thread.Sleep(100);
                Console.CursorTop = 4;
                Console.CursorLeft = 90;
                Console.Write("-"); System.Threading.Thread.Sleep(100);
                Console.CursorTop = 4;
                Console.CursorLeft = 90;
                Console.Write("|"); System.Threading.Thread.Sleep(100);
                Console.CursorTop = 4;
                Console.CursorLeft = 90;
                Console.Write("/");
                System.Threading.Thread.Sleep(100);
            }
        }
        private static void Main(string[] args)
        {
            EscreveConsole().ConfigureAwait(false);// queria q isso executasse independentemente

TarefaBaseAsync().Wait();
        }

1 answer

0


The goal was to create a progress bar, I managed to develop something like below.

public class ProgressBar : IDisposable, IProgress<double>
    {
        public int blockCount = 20;

        private readonly TimeSpan animationInterval = TimeSpan.FromSeconds(1.0 / 8);
        private const string animation = @"|/-\";

        private readonly Timer timer;

        private double currentProgress = 0;
        private string currentText = string.Empty;
        private bool disposed = false;
        private int animationIndex = 0;

        public ProgressBar()
        {

            if (!Console.IsOutputRedirected)
            {
                ResetTimer();
            }
        }


        public void Report(double value)
        {
            // Make sure value is in [0..1] range
            value = Math.Max(0, Math.Min(1, value));
            Interlocked.Exchange(ref currentProgress, value);
        }

        private void TimerHandler(object state)
        {
            lock (timer)
            {
                if (disposed) return;

                int progressBlockCount = (int)(currentProgress * blockCount);
                int percent = (int)(currentProgress * 100);
                string text = string.Format("[{0}{1}] {2,3}% {3}",
                    new string('#', progressBlockCount), new string('-', blockCount - progressBlockCount),
                    percent,
                    animation[animationIndex++ % animation.Length]);
                UpdateText(text);

                ResetTimer();
            }
        }

        private void UpdateText(string text)
        {
            // Get length of common portion
            int commonPrefixLength = 0;
            int commonLength = Math.Min(currentText.Length, text.Length);
            while (commonPrefixLength < commonLength && text[commonPrefixLength] == currentText[commonPrefixLength])
            {
                commonPrefixLength++;
            }

            // Backtrack to the first differing character
            StringBuilder outputBuilder = new StringBuilder();
            outputBuilder.Append('\b', currentText.Length - commonPrefixLength);

            // Output new suffix
            outputBuilder.Append(text.Substring(commonPrefixLength));

            // If the new text is shorter than the old one: delete overlapping characters
            int overlapCount = currentText.Length - text.Length;
            if (overlapCount > 0)
            {
                outputBuilder.Append(' ', overlapCount);
                outputBuilder.Append('\b', overlapCount);
            }

            Console.Write(outputBuilder);
            currentText = text;
        }

        private void ResetTimer()
        {
            timer.Change(animationInterval, TimeSpan.FromMilliseconds(-1));
        }

        public void Dispose()
        {
            lock (timer)
            {
                disposed = true;
                UpdateText(string.Empty);
            }
        }

    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.