Is it possible to abort a synchronous method that executes for a long time?
I have the method Test that calls the LongRunningMethod
method that consumes a lot of memory and CPU, in case it lasts longer than 30 seconds, I want to abort it. However, after an exception is thrown, the CPU and memory are still increasing, although the task is completed.
Code:
static async Task<string> Test (string input)
{
var tokenSource = new CancellationTokenSource();
var task = LongRunningMethod(input, tokenSource.Token)
.WaitAsync(TimeSpan.FromSeconds(30));
try
{
var result = await task;
return result;
}
catch (Exception ex)
{
// if the timeout is thrown, the LongRunningMethod still executes in background
// and increase memory and CPU
}
}
static Task<string> LongRunningMethod(string input, CancellationToken token)
{
var task= Task.Run(() =>
{
SynchronousMethodThatConsumesMemoryAndCpu(input);
return "end";
},
token);
return task;
}