[英]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. 我想在控制台的不同位置上显示消息,但是当我尝试将光标位置设置为左50,前60时,它得到了更改,然后将打印“ A”,“ B”,因为还有另一个线程“ th”也会在控制台上的不同位置显示消息。因此,它还在左侧和顶部访问Cursor属性。 I want when Man() function set cursor location,at that time no other thread will change it. 我想当Man()函数设置光标位置时,那时没有其他线程可以更改它。
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. 由于您正在创建Program类的两个实例,因此“ this”将引用两个不同的对象,因此无法将其中的一部分代码保留在其中,而另一部分代码已经包含在其中。
One way to solve this problem will be to lock over a static object. 解决此问题的一种方法是锁定静态对象。
The better approach will be to optimise your code. 更好的方法是优化代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.