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.
Asked
Active
Viewed 55 times
0

chinh nguyen van
- 729
- 2
- 7
- 18
-
do you mean cancel running or compiling? – Lei Yang Mar 10 '17 at 09:26
-
@LeiYang mean cancel the running dynamic compiled code – chinh nguyen van Mar 10 '17 at 09:29
-
what about `Process.Kill` – Lei Yang Mar 10 '17 at 09:29
-
@LeiYang how and where exactly you put Process.Kill – chinh nguyen van Mar 10 '17 at 09:30
-
then how did you start/run it? – Lei Yang Mar 10 '17 at 09:33
-
I am running methodInfo.Invoke(myobject, invokeInput) – chinh nguyen van Mar 10 '17 at 09:48
-
2It is crucial that you sandbox the code so they can't p0wn your server. That requires an AppDomain, unloading it also automagically aborts a thread that is running in the AD. Focus on making the safe, the rest comes along for free. – Hans Passant Mar 10 '17 at 10:22
1 Answers
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