Performing multiple parrallel tasks and overwriting each line for

I am new to programming, but I have a question:

How can I show a different output from a task (I have to use tasks) on different lines in the console? In addition, I want to rewrite the lines every time, so the output should show:

i // overwrite this line every time.

j // overwrite this line every time.

I tried using SetCursorPosition, but it causes a collision between the task that occurs after that.

Example of a mini-code (I hope this becomes clear):

Task a = Task.Run(() =>
{
    int i;
    for (i = 0; i <= 1000000; i++)
    {
        Console.SetCursorPosition(Console.CursorLeft, 0); // ? 
        Console.WriteLine("{0}", i);
    }
});

Task b = Task.Run(() =>
{
    int j;
    for (j = 0; j <= 1000000; j++)
    {
        Console.SetCursorPosition(Console.CursorLeft, 3); // ?
        Console.WriteLine("{0}",j);
    }
});

Console.ReadLine();

Thanks in advance:)

+4
source share
2 answers

Console ( , - , ):

var consoleLock = new object();

Task.Run(() =>
{
    for (int i = 0; i <= 1000000; i++)
    {
        Thread.Sleep(1); // to simulate some work
        lock(consoleLock)
        {
            Console.SetCursorPosition(Console.CursorLeft, 0);
            Console.WriteLine(i);
        }
    }
});

Task.Run(() =>
{
    for (int j = 0; j <= 1000000; j++)
    {
        Thread.Sleep(1); // to simulate some work
        lock(consoleLock)
        {
            Console.SetCursorPosition(Console.CursorLeft, 3);
            Console.WriteLine(j);
        }
    }
});

Console.ReadLine();
+2

, . .

, ThreadSafe . , , ( SetCursorPosition()).

static object locker = new object();
static int iCommon = 0;
static int jCommon = 0;

static void WriteText()
{
    lock(locker)
    {
        var text = string.Format("i = {0}{1}j = {2}", 
                                    iCommon, Environment.NewLine, jCommon);
        Console.SetCursorPosition(0, 
                                  Console.CursorTop == 0 ? 0 : Console.CursorTop - 1);
        Console.Write(text);
    }
}

static void Main(string[] args)
{
    Task a = Task.Run(() =>
    {
        for (int i = 0; i <= 15; i++)
        {
            Thread.Sleep(700); //just to demonstrate the display change
            iCommon = i;
            WriteText();
        }
    });

    Task b = Task.Run(() =>
    {
        for (int j = 0; j <= 10; j++)
        {
            Thread.Sleep(1150); //just to demonstrate the display change
            jCommon = j;
            WriteText();
        }
    });
    Console.ReadLine();
}
+1

Source: https://habr.com/ru/post/1610393/


All Articles