Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the result of a task when using Task.WhenAny to account for a timeout

Tags:

c#

xamarin

I need to add a timeout feature to the task calls in a mobile app. I attempted to complete this by using Task.WhenAny as shown below. This returns the task that finishes first. My problem is that originally I was getting the return value from this task, and I still need it if the task does not get timed out.

Task task = restService.GetRequestAsync(articleAdr, articleParams);
var response = await Task.WhenAny(task, Task.Delay(1000, cts.Token));

response is simply the task that was completed first. How do I get it's result?

like image 939
Matt Migdal Avatar asked Jan 29 '17 19:01

Matt Migdal


Video Answer


1 Answers

I can think of three different possibilities for this scenario.

The first two can be found in Peter Bons' answer.

The third is storing off your two tasks then checking the status after the await Task.WhenAny() is completed.

var workerTask = restService.GetRequestAsync(articleAdr, articleParams);
var cancellationTask = Task.Delay(1000, cts.Token);

await Task.WhenAny(workerTask, cancellationTask);
if (workerTask.Status == TaskStatus.RanToCompletion)
{
  // Note that this is NOT a blocking call because the Task ran to completion.
  var response = workerTask.Result;

  // Do whatever work with the completed result.
}
else
{
  // Handle the cancellation.
  // NOTE: You do NOT want to call workerTask.Result here. It will be a blocking call and will block until 
  // your previous method completes, especially since you aren't passing the CancellationToken.
}
like image 177
Cameron Avatar answered Oct 13 '22 20:10

Cameron