Time limiting a method in C#

后端 未结 6 2016
小蘑菇
小蘑菇 2021-02-02 17:16

I have a Game framework where there is a list of Bots who implement IBotInterface. These bots are custom made by user with the only limitation that they must implement the inter

6条回答
  •  礼貌的吻别
    2021-02-02 17:46

    I think the only problem is an inverted conditional. You should call EndInvoke only if the task completed successfully.

    Rough suggestion:

    var goodBots = new List();
    var results = new IAsyncResult[Bots.Count];
    var events = new WaitHandle[Bots.Count];
    int i = 0;
    foreach (IBot bot in Bots) {
        NewGame del = bot.NewGame;
        results[i] = del.BeginInvoke(Info, null, null);
        events[i++] = r.AsyncWaitHandle;
    }
    WaitAll(events, RoundLimit);
    var goodBots = new List();
    for( i = 0; i < events.Count; i++ ) {
        if (results[i].IsCompleted) {
            goodBots.Add(Bots[i]);
            EndInvoke(results[i]);
            results[i].Dispose();
        }
        else {
            WriteLine("bot " + i.ToString() + " eliminated by timeout.");
        }
    }
    Bots = goodBots;
    

    Even better would be to explicitly spin up a thread for each bot, that way you could suspend the misbehaving bots (or dial down their priority) so that they don't continue to steal CPU time from the good bots.

提交回复
热议问题