-3

Following the good ideas that I was given in my previous question on how to wait for processes to complete I would like to ask something related.

This time I don't have two processes to do one after another, but only one process that has to proceed after it gets a positive response from a server. Something like this

private async Task<bool> requestPermission()
{
    var result = await sendRequestToServer();
    return result;
}

private async Task Process1()
{ bool amIOktoGo=false;
   amIOktoGo= await requestPermission();
   while(!amIOktoGo)
   {
      await Task.Delay(1000);
     amIOktoGo= await requestPermission();
    } 

   
  //Finally! Do some more stuff involving awaits and requests from the server

}

Again, this seems overly complicated. Is there a simpler way to do this?

halfer
  • 19,824
  • 17
  • 99
  • 186
KansaiRobot
  • 7,564
  • 11
  • 71
  • 150

1 Answers1

0

Don't reinvent the wheel. There is a library Polly which supports exactly the scenario for retry

Here's an async example for your case. If there is an exception or result returned false, it retries your action async.

await Policy
  .Handle<Exception>()
  .OrResult<bool>(b => !b)
  .WaitAndRetry(new[]
  {
     TimeSpan.FromSeconds(1),
  })
  .RetryAsync()
  .ExecuteAsync(() => requestPermission());
Antoine V
  • 6,998
  • 2
  • 11
  • 34