Programming in C# — Question 65

You are implementing a method named ProcessData that performs a long-running task. The ProcessData() method has the following method signature: public void ProcessData(List<decimal> values, CancellationTokenSource source, CancellationToken token)
If the calling code requests cancellation, the method must perform the following actions:
✑ Cancel the long-running task.
✑ Set the task status to TaskStatus.Canceled.
You need to ensure that the ProcessData() method performs the required actions.
Which code segment should you use in the method body?

Answer options

Correct answer: C

Explanation

The correct answer is C because the method token.ThrowIfCancellationRequested() will throw an exception if cancellation is requested, which allows the process to terminate properly and update the status. Option A only checks for cancellation without throwing an exception, meaning the task will continue running. Option B throws an exception without checking for cancellation, and D cancels the token source but does not handle the task's cancellation directly.