0

In Asp.Net Core controller I'd like to do something like below:

// Start preparing a report as string:
string reportText = await ReportService.PrepareAsync();

// wait for 10 seconds; how?
if (secondsPassed > 10) 
{
    // When finished, save the report text to database,
    // and notify a user by SignalR
}
else 
{
    // Report finished within 10 seconds; 
    // return immediately as a json response
    return Ok(new { Report = reportText });
}

What is the recommended way of doing the above or similar task?

synergetic
  • 7,756
  • 8
  • 65
  • 106
  • You mean use a timeout? You'll find many similar questions that show how to use `Task.Delay` and `Task.WhenAny` – Panagiotis Kanavos Apr 09 '19 at 13:02
  • The asynchronous operation is `ReportService.PrepareAsync();` which returns a task. `await` doesn't make anything run asynchronously, it *awaits* already running asynchronous operations. This means that you can store the Tasks returned by `ReportService.PrepareAsync()` and `Task.Delay` in variables and await both of them with `var firstTask=await Task.WhenAll(delayTask,prepareTask);`. The first task to finish will be stored in the `firstTask` variable. – Panagiotis Kanavos Apr 09 '19 at 13:05

0 Answers0