![](/img/trans.png)
[英]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.