1

I have an async task with this inside :

while (!cancellationToken.IsCancellationRequested)
{
    Console.Write("Enter workload : ");
    if (!int.TryParse(Console.ReadLine(), out var workTime)) continue;

    Console.Write("Enter the duration of a GC collection (in ms) : ");
    if (!int.TryParse(Console.ReadLine(), out var gctime)) continue;

    Console.Write("Enter the number of requests between 2 GCs : ");
    if (!int.TryParse(Console.ReadLine(), out var gcinter)) continue;

    *do irrelevant stuff here*
}

Currently the check to leave the loop if cancellation is requested happens only at the start of the loop. So if the cancellation is requested and the user hasn't entered yet the workload, he'll be able to continue through the steps of the method. I don't want that.

Is there an elegant way (i.e not check the cancellation token between each line of the method) to just cancel the task whenever requested, even if the user is writing something or just independently of what's happening in the method ?

Thanks in advance :)

Cholesterol
  • 177
  • 2
  • 10

1 Answers1

0

Well, thread.Abort () could be the solution in your case. But it has its own pandora box of problems. You might wanna rethink on your logic, to why you want to abort thread immediately. Tasks don't have abort. It's because aborting a thread will cause extreme level of ambiguity to program state and stability

You might wanna look at following problems (they also want to do something like you):
Is it possible to abort a Task like aborting a Thread (Thread.Abort method)?
Cancel/Abort a Task in C#