简体   繁体   中英

How lock Console class properties so only one thread can access them at one time

I want to display message on different location of console, but when i try to set cursor location as left 50,top 60, it got change before it will print 'A','B' because there is another thread "th" which is also displaying message on console on different location.So it is also accessing Cursor properties left and top. I want when Man() function set cursor location,at that time no other thread will change it.

static void Main(string[] args)
    {
        Thread th = new Thread(() => new Program().Hello(50, 60));
        th.Start();
        new Program().Man();
    }   
    public void Hello(int left, int top)
    {
        int i = 0;
        Console.CursorLeft = left; Console.CursorTop = top;
        Console.ForegroundColor = ConsoleColor.DarkGreen;`
        Console.Write("Processing");
        while (true)
        {
            i = 0;
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            while (i < 20)
            {
                Console.Write("*");
                i++;
            }
            Console.ForegroundColor = ConsoleColor.Black;
            Console.Write("********************");
        }
    }

    public void Man()
    {
            Console.CursorLeft = 50;
            Console.CursorTop = 60;
            Console.Write("A");
            Console.Write("B");
            Console.Write("C");
            Console.Write("D");

    }

The problem with your code is that your locking on an instance through "this" reserved word. Since you're creating two instances of Program class the "this" will refer to two different object and hence it fails to keep one section of code out while other is already inside.

One way to solve this problem will be to lock over a static object.

The better approach will be to optimise your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM