I'm using a Lua interpreter library ('NeoLua') to allow the user to write code in my app. I'm running the interpreter in a task. I would like to be able to start and stop the program using two buttons, but I can't find a way to end the task reliably.
public partial class Form1 : Form {
Lua lua = new();
LuaGlobal g;
Task interpreterTask;
private void StartProgram() {
g = lua.CreateEnvironment();
dynamic dg = g;
dg.custom_function = new Action<int>(CustomFunction); // add my custom functions to the lua environment
interpreterTask = Task.Factory.StartNew(() => {
string pgrm = System.IO.File.ReadAllText("program.lua");
g.DoChunk(pgrm, "program.lua");
}
);
}
private void StopProgram() {
// ?
}
public void CustomFunction(int x) {
// do stuff
}
}
I could easily use the CancellationTokenSource
class to cancel the task inside the custom functions that I implement in C#, since they should regularily be called in the Lua program. But what if the user writes an infinite loop ? The DoChunk
method (that comes from an external library which does not provide any way of properly stopping the interpreter) would never return and I would never be able to check for cancellation.
I am looking for a way to completely 'kill' the task, similarily to how I would kill a process or abort a thread (which I can't do because I'm using .NET 6.0). Whould I have better luck by running the interpreter in a separate thread ? Should I just stick with checking for a cancellation tocken in each function (and force the user to close the whole app if they unintentionally create an infinite loop) ?