Lock Statement C# - Console.SetCursorPositon

时间:2018-05-05 21:09:51

标签: c# multithreading locking

我想创建一个同时移动两个玩家的程序。问题是我不知道如何阻止每个玩家在其他位置显示他们的符号。

代码:

class Player
{
    public int X { get; set; }
    public int Y { get; set; }

    private char symbol;
    private object Object = new object();
    public Player(char symbol)
    {
        this.symbol = symbol;            
    }

    public void Move(object obj)
    {
        if (!(obj is Random))
            throw new Exception("Object isnt Random instance");
        Random rnd = obj as Random;

        X = rnd.Next(50);
        Y = rnd.Next(50);

        while (true)
        {
            int xChange = 0, yChange = 0;

            if (rnd.Next(100) < 50)
                xChange = rnd.Next(-1, 2);
            else
                yChange = rnd.Next(-1, 2);

            if (X + xChange < 0 || X + xChange > Console.BufferWidth || Y + 
            yChange < 0 || Y + yChange > Console.BufferHeight)
                continue;

            lock (Object)//critical section
            {
                Console.SetCursorPosition(X, Y);
                Console.Write(" ");
                Console.SetCursorPosition(X + xChange, Y + yChange);
                Console.Write(symbol);
            }

            X = X + xChange;
            Y = Y + yChange;

            Thread.Sleep(1000);
        }
    }
}

class GameManager
{
    private List<Player> players = new List<Player>();
    private Dictionary<Player, Thread> threads = new Dictionary<Player, 
    Thread>();
    public static bool simulationStop = false;
    private static Random rnd = new Random();

    public GameManager()
    {
        players.Add(new Player('O'));
        players.Add(new Player('X'));
    }

    public void Go()
    {
        Console.CursorVisible = false;
        CreateThreads();

        while(simulationStop == false)
        {
            Thread.Sleep(1000);
        }

        //close all Threads at the end of the simulation
        foreach (KeyValuePair<Player, Thread> pair in threads)
        {
            threads[pair.Key].Abort();
        }
    }

    private void CreateThreads()
    {
        foreach(Player p in players)
        {
            threads.Add(p, new Thread(new 
            ParameterizedThreadStart(p.Move)));

            threads[p].Start(rnd);
        }
    }
}

我使用lock语句来防止线程同时进入临界区,但由于某种原因它不起作用......

提前致谢!

0 个答案:

没有答案