0

I am developing a website which let user type in their code and run to show output (just like Linqpad). I used CSharpCodeProvider but I also want to set timeout for the code, so that it will not break system if their code is too slow or have infinite loop. Because the code is dynamic from user, how can I achieve that? I tried CancellationToken but look like it need to be called from inside the dynamic source code, not outside.

chinh nguyen van
  • 729
  • 2
  • 7
  • 18

1 Answers1

0

I figured it out, I forgot to check IsCancellationRequested, below is the working code:

var cts = new CancellationTokenSource();

var newTask = Task.Factory.StartNew(state =>
{
    var token = (CancellationToken)state;
    if (!token.IsCancellationRequested)
    {
        var invokeInput = new object[] { input };
        var output = mi.Invoke(o, invokeInput);
    }
}, cts.Token, cts.Token);


if (!newTask.Wait(timeout, cts.Token))
{
    cts.Cancel();
    throw new Exception("The operation has timed out.");
}
chinh nguyen van
  • 729
  • 2
  • 7
  • 18