In my assignment I am executing a long running NodeJs script from C# using EdgeJs. Since the script may take a long time to execute, I also want to provide user an option to Cancel the script execution in the middle. The cancellation status is maintained in the database and function IsScripteExecutionCancelled returns true if the user decides to cancel the execution.
To achieve this I am executing script in a background thread using Task.Run(). The main thread contains a while loop that runs until the ScriptExecution is over or is cancelled. I can solve this problem using native System.Threading.Thread, but here I am trying to do it using TPL. Here is the code I have put in place:
bool executionStarted = false;
bool taskCompleted = false;
Result returnValue;
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task executionTask;
while (!(taskCompleted || token.IsCancellationRequested))
{
if (!executionStarted)
{
executionStarted = true;
executionTask = Task.Run(() =>
{
returnValue = ExecuteScript();
taskCompleted = true;
}, token);
}
bool taskExecutionCancelled = IsScripteExecutionCancelled();
if (taskExecutionCancelled)
{
tokenSource.Cancel();
}
}
if(token.IsCancellationRequested)
returnValue= GetDefaultValueForCancellation();
return returnValue;
So, if IsScripteExecutionCancelled returns true the program will come out of the loop and will check if the script was cancelled, in which case I will return a default response. If the ExecuteScript completes my program will return the value returned by function ExecuteScript. I am able to get the desired results using this implementation however I would like to get it validated.
Question: Is it the right way to address this problem?