Marko Žerajić
Marko Žerajić

Reputation: 201

Abort roslyn script execution

I'd like to implement timeout mechanism for scripts, executed through Roslyn, so I need a way to abort a script execution. The only solution I found so far, is executing the script inside a thread and terminating it, but it's obviously a flawed solution.

Is there a better way to do this?

Upvotes: 2

Views: 412

Answers (2)

MB_18
MB_18

Reputation: 2251

First create a new thread and put your code inside the thread as an action. Then call the Thread.Start method to begin execution. Use Thread.Join method to wait until the thread completes its execution.

In the below code, if the thread execution does not complete in 6 seconds then the thread is interrupted.

Here is the code:

Thread thread = new Thread(() => {
    try
    {
          // your code related to Roslyn is here
          // ...
    }
    catch (Exception ex)
    {
    }

});

thread.Start();

if (!thread.Join(TimeSpan.FromSeconds(6)))
{
    thread.Interrupt();
}

The above code ends compilation after 6 seconds.

Upvotes: 0

Jason Malinowski
Jason Malinowski

Reputation: 19021

Other than you launching a separate process and killing that instead (to avoid the standard pitfalls of Thread.Abort()), that's the best you can do. Given the script code can be more or less arbitrary, there really couldn't be a better option. All it takes is your script to do Thread.Sleep(Timeout.Infinite) and there's nothing the scripting engine could do to recover that.

Upvotes: 3

Related Questions