Search code examples
c#tasktext-cursor

Running multiple tasks parrallel and overwriting each line in for


I'm pretty new to programming, but I have a question:

How could I show different task output (I should use the tasks) in different lines, in the console? Also, I want to overwrite the lines each time , so the output should show:

i // overwriting this line everytime.

j // overwriting this line everytime.

I tried using SetCursorPosition, but it makes a collision between the task ouput somewhy.

A mini code sample (hope this makes it clearer):

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();

Thank You in advance :)


Solution

  • You need to synchronize access to Console for different tasks (I am not fixing position part if there is any problem, but an obvious synchronization problem):

    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();