Using Console.SetCursorPosition asynchronously

无人久伴 提交于 2020-12-13 03:19:28

问题


To experiment with updating percentages of progress items in the console, I've made a small test console application:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleProgressTest
{
    class Program
    {
        public class ConsoleItem
        {
            public string Item { get; set; }
            public int ConsoleLocLeft { get; set; }
            public int ConsoleLocTop { get; set; }
        }

        static void Main(string[] args)
        {
            List<string> tempList = GenerateTempList();
            List<string> selection = GetSelectionFromList(tempList);

            List<ConsoleItem> consoleItems = new List<ConsoleItem>();
            foreach (string item in selection)
            {
                Console.Write($"Selected: \"{item}\" ");

                ConsoleItem consoleItem = new ConsoleItem()
                {
                    Item = item,
                    ConsoleLocLeft = Console.CursorLeft,
                    ConsoleLocTop = Console.CursorTop
                };
                consoleItems.Add(consoleItem);

                Console.Write("\n");
            }

            int finalCursorLeft = Console.CursorLeft;
            int finalCursorTop = Console.CursorTop;

            Console.CursorVisible = false;
            List<Task> progressTasks = new List<Task>();
            foreach (ConsoleItem item in consoleItems)
            {
                Task itemTask = IncrementProgress(item);
                progressTasks.Add(itemTask);
            }

            Task.WaitAll(progressTasks.ToArray());

            Console.CursorVisible = true;
            Console.SetCursorPosition(finalCursorLeft, finalCursorTop);
            Console.WriteLine("All progress finished. Press any key to exit");
            Console.Read();
        }

        private static List<string> GenerateTempList()
        {
            List<string> result = new List<string>()
            {
                "Item 0",
                "Item 1",
                "Item 2",
                "Item 3",
                "Item 4",
                "Item 5"
            };

            return result;
        }

        public static List<string> GetSelectionFromList(List<string> listToDisplay)
        {
            foreach (string item in listToDisplay)
                Console.WriteLine("(" + listToDisplay.IndexOf(item) + ") " + item);

            Console.WriteLine("Which # would you like?");
            string input = Console.ReadLine();
            List<string> result = new List<string>();
            foreach (string indexStr in input.Split(','))
            {
                if (indexStr.Contains("-"))
                {
                    int startOfRange = Convert.ToInt32(indexStr.Split('-')[0]);
                    int endOfRange = Convert.ToInt32(indexStr.Split('-')[1]);
                    for (int i = startOfRange; i <= endOfRange; i++)
                    {
                        if (i < 0 || i > listToDisplay.Count - 1)
                        {
                            Console.WriteLine("Could not find index " + i);
                            continue;
                        }

                        result.Add(listToDisplay[i]);
                    }
                }
                else
                {
                    int index = Convert.ToInt32(indexStr);
                    if (index < 0 || index > listToDisplay.Count - 1)
                    {
                        Console.WriteLine("Could not find index " + index);
                        continue;
                    }

                    result.Add(listToDisplay[index]);
                }
            }

            return result;
        }

        public static async Task IncrementProgress(ConsoleItem item)
        {
            Random r1 = new Random((int)DateTime.Now.Ticks);
            int millisecondDelay = r1.Next(1000, 5000);

            Random r2 = new Random((int)DateTime.Now.Ticks);
            int percentage = 0;
            while (percentage < 100)
            {
                await Task.Run(() => Thread.Sleep(millisecondDelay));
                percentage = r2.Next(percentage, 101);
                UpdatePercentange(item, percentage);
            }
        }

        private static void UpdatePercentange(ConsoleItem item, double percentage)
        {
            Console.SetCursorPosition(item.ConsoleLocLeft, item.ConsoleLocTop);
            Console.Write($"({percentage}%)");
        }
    }
}

I have noticed something odd when updating the console:

recording1

(notice how the process sometimes gets duplicated when Item 2 reaches 96%)

But if I put in a Debug.WriteLine at the beginning of my UpdatePercentage method like this:

private static void UpdatePercentange(ConsoleItem item, double percentage)
{
    Debug.WriteLine($"Updating percentage of {item.Item} at {item.ConsoleLocLeft}, {item.ConsoleLocTop} ({percentage})");
    Console.SetCursorPosition(item.ConsoleLocLeft, item.ConsoleLocTop);
    Console.Write($"({percentage}%)");
}

Then it works just fine:

recording2

Any idea what might be causing this?


回答1:


You could lock your update requests using a common object (an object sync = new object() is enough) which would prevent your problem.

Currently, this is what happens:

  • (thread 1) SetCursorPosition
  • (thread 2) SetCursorPosition (cursor is now where ever thread two wants to write)
  • (thread 1 or 2) Console.Write
  • (the other thread) Console.Write

So your console output could look like that:

    private static object _sync = new object();

    private static void UpdatePercentange(ConsoleItem item, double percentage)
    {
        lock(_sync)
        {   
            Console.SetCursorPosition(item.ConsoleLocLeft, item.ConsoleLocTop);
            Console.Write($"({percentage}%)");
        }
    }


来源:https://stackoverflow.com/questions/55519275/using-console-setcursorposition-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!