[英]how to ensure only one thread can access an instance of a collection type at a time
[英]How lock Console class properties so only one thread can access them at one time
我想在控制台的不同位置上显示消息,但是当我尝试将光标位置设置为左50,前60时,它得到了更改,然后将打印“ A”,“ B”,因为还有另一个线程“ th”也会在控制台上的不同位置显示消息。因此,它还在左侧和顶部访问Cursor属性。 我想当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");
}
您的代码的问题是您通过“此”保留字锁定实例。 由于您正在创建Program类的两个实例,因此“ this”将引用两个不同的对象,因此无法将其中的一部分代码保留在其中,而另一部分代码已经包含在其中。
解决此问题的一种方法是锁定静态对象。
更好的方法是优化代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.