PrepAway - Latest Free Exam Questions & Answers

Which code segment should you use in the method body?

You are implementing a method named ProcessReports that performs a long-running task. The
ProcessReports() method has the following method signature:
public void ProcessReports(List<decimal> values,CancellationTokenSource cts, CancellationToken ct)
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 ProcessReports() method performs the required actions.
Which code segment should you use in the method body?

PrepAway - Latest Free Exam Questions & Answers

A.
if (ct.IsCancellationRequested)
return;

B.
ct.ThrowIfCancellationRequested() ;

C.
cts.Cancel();

D.
throw new AggregateException();

6 Comments on “Which code segment should you use in the method body?

  1. Cees says:

    Shouldn’t it be C?

    The ThrowIfCancellationRequested() throws an OperationCanceledException: https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken.throwifcancellationrequested?view=netframework-4.7.1#System_Threading_CancellationToken_ThrowIfCancellationRequested
    which is not really a nice way to cancel the task.

    Instead, cts.Cancel() will communicate a cancel request to the associated token, after which the ct.IsCancellationRequested will be set to true: https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.cancel?view=netframework-4.7.1#System_Threading_CancellationTokenSource_Cancel




    2



    8
    1. khoa_chung_89 says:

      There’s a requirement in the question: Set the task status to TaskStatus.Canceled.
      If you just call the cancel on token source, the task will end up with status RanToCompletion – in another word, the task caller have no idea how the task was completed. You have to throw the exception and let the task caller catch that exception. In that case, the task will be end up with Canceled status.
      B is correct.




      2



      0

Leave a Reply