等待来自其他帖子

时间:2016-01-23 18:43:30

标签: c# multithreading

我正在尝试实施简单的扑克游戏(宠物项目)。玩家可以做两个动作:折叠或检查。基本场景非常简单:两名玩家开始游戏。第一个动作是player1。他可以折叠或检查。之后,player2可以折叠或检查。 我想写出适当的测试和玩家可以做玩家的动作。

我的原型代码看起来像是跟随。

Player player1 = new Player(1);
Player player2 = new Player(2);
List<Player> players = new List<Player>() { player1, player2 };          

Game hand = new Game();
hand.Players = players;

Thread game = new Thread(hand.WaitForPlayersAnswer);
game.Start();
Thread p1 = new Thread(player1.Check);
p1.Start();   
Thread p2 = new Thread(player2.Fold);
p2.Start();

播放器:

public class Player
{
    private SemaphoreSlim _sem;
    private int _i;

    public Player(int i)
    {
        _i = i;
    }

    public void Check()
    {
        while (_sem == null)
        { }
        Console.WriteLine(_i + ": Check");
        _sem.Release();

    }

    public void Fold()
    {
        while (_sem == null)
        { }
        Console.WriteLine(_i + ": Fold");
        _sem.Release();
    }

    public void DoAction(SemaphoreSlim sem)
    {
        _sem = sem;
        sem.Wait();
        _sem = null;
    }
}

游戏:

public class Game
{
    public List<Player> Players { get; set; }

    public void WaitForPlayersAnswer()
    {
        var token = new SemaphoreSlim(0);
        foreach (var player in Players)
        {
            player.DoAction(token);
        }
    }
}

我相信这是实现目标的更好方式。我怎样才能做得更好?

0 个答案:

没有答案