Guerrilla
Guerrilla

Reputation: 14866

Set Console cursor position in threadsafe way

I have a method that is accessed by many Tasks concurrently. I am reporting progress like this:

Console.WriteLine("Processed: " + Interlocked.Increment(ref progress).ToString());
Console.SetCursorPosition(0,  Console.CursorTop - 1);

I reset the Console cursor position so next time it reports it overwrites the last number so I can have nice output on the screen.

I end up getting problem where it seems a thread reads new position wrong and it jumps up an extra line and messes up my other output information in the console.

I am not sure what I need to lock in order to lock the console so from time of reading to time of updating it cannot be read again and mess up the output (if that is actually the problem, I am not sure).

I'd like to be able to fully control what line it's outputting on so need to work out way to stop multiple threads messing up the position.

Upvotes: 0

Views: 1330

Answers (1)

YaniMan
YaniMan

Reputation: 303

You can lock anything. Just create some object if there's no other object you think you could use, and then lock that.

var lck = new object();

void method()
{
    lock(lck)
    {
        Console.WriteLine...
        Console.SetCursorPosition...
    }
}

Upvotes: 6

Related Questions