Time limiting a method in C#

后端 未结 6 2018
小蘑菇
小蘑菇 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:53

    A .NET 4.0 Task gives you considerably flexibility with regard to cancelling.

    Run the delegate in a Task that you've passed a CancelationToken into, like this.

    There's a fuller example here.

    edit

    In light of the feedback, I believe that the right answer is to follow this plan:

    1. Limit the AI using CAS, so that it can't access threading primitives or mess with files.

    2. Give it a heartbeat callback that it is morally obligated to call from inside long loops. This callback will throw an exception if the thread has taken too long.

    3. If the AI times out, log a weak move for it, and give it a short amount of time to call that callback. If it doesn't, just put the thread to sleep until its next turn. If it never does snap out of it, it will keep logging weak moves until the process kills it for being a background thread.

    4. Profit!

提交回复
热议问题