Which code segment should you use in the method body?

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?

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?

A.
if (token.IsCancellationRequested)
return;

B.
throw new AggregateException();

C.
token.ThrowIfCancellationRequested();

D.
source.Cancel();



Leave a Reply 3

Your email address will not be published. Required fields are marked *


j

j

A?
CancellationTokenSource cancellationTokenSource=new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
Task task = Task.Run(() =>
{
while(!token.IsCancellationRequested)
{
Console.Write(“*”);
Thread.Sleep(1000);
}
}, token);
Console.WriteLine(“Press enter to stop the task”);
Console.ReadLine();
cancellationTokenSource.Cancel();
Console.WriteLine(“Press enter to end the application”);
Console.ReadLine();

zh

zh

The requests are for the task ProcessData:

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.

“the method is the ProcessData”

A: if (token.IsCancellationRequested) return; – this is just checking if the task was canceled

B: throw new AggregateException(); – incorrect

C: token.ThrowIfCancellationRequested(); – “If the calling code requests cancellation” this is the correct one.

D: source.Cancel(); – This is used by the calling method

See this documentation: https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx