Trying to run script (using Roslyn Scripting API):
var source = "while(true) { }";
return CSharpScript.EvaluateAsync(source).Result;
It will run forever. How to interrupt it?
I don't mind using other script engine, though asking for one is off-topic. I've found similar questions (example), but they are not helpful.
Background: I want to add support for C# user-written scripts to my software. I want to run scripts in sandbox, so ability to interrupt scripts is vital. In past I had some experience with CodeDOM, but I fail to find a way to interrupt scripts there too.
Thoughts:
- I could pre-process user-written text and insert my code (checks for
CancellationToken
andreturn/throw
) after each line. But above example is immune to such technique and I'd then must go complex route of syntax parser (don't have experience with that, thoughts?). - I could provide a method, which user have to explicitly call in his script problematic places (e.g. inside loops), but user may simply decide to ignore that.
- Is there a way to run script step-by-step? Sandbox-debugger mode? Then I'd be able to check external request to terminate script and stop debugging.
What are the other possibilities? Has anyone implemented safe user-written scripting yet?