Time limiting a method in C#

后端 未结 6 2025
小蘑菇
小蘑菇 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 18:01

    As I mentioned on @Lasse's answer, you really should consider using Code Access Security to limit what the bots are allowed to do on the system. You can really restrict what the bots are allowed to do execution wise (including removing their ability to access threading APIs). It might be worth considering treating each bot as if it was a virus since you aren't in control of what it could do to your system and I'm assuming that your game will be running as a full-trust application.

    That said, if you restrict what each bot does with CAS, you may be able to terminate the thread without fear of corrupting your system. If a bot is stuck in an infinite loop, I suspect that your only recourse will be to terminate the thread since it will, programatically, never be able to reach any code that would check for a Thread.Abort signal.

    This MSDN article may give you some guidance on how to more effectively terminate a run-away thread using a TerminateThread function.

    You really have to try all of these things out and prove to yourself which may be the best solution.

    Alternatively, if this a competitive game and the bot authors have to play fair, have you considered having the game give each bot a "turn token" that the bot has to present with each action that it wants to invoke and when the game flips turns, it gives all the bots a new token. This may allow you to now only have to worry about run-away threads and not robots who take to long on their turn.

    Edit

    Just to add a place for people to go look Security Permission Flag Enumerations will give you a sense of where to start. If you remove the SecurityPermissionFlag.ControlThread permission (as an example, only giving the code permission to execute and excluding ControlThread) you will remove their

    Ability to use certain advanced operations on threads.

    I don't know the extent of the operations that are inaccessible, but it will be an interesting exercise for the weekend to figure that out.

提交回复
热议问题