0

I need to integrate an API into my development with a specific scenario called "Time Out Reversal" (TOR)

This means, succintly, to comply with the following requirements:

  • Initiate a request by invoking an endpoint
  • If a response is not received within a defined time out
  • start a reversal request by invoking another endpoint

While the requirements seems very clear to me, I really haven't found a way to implement it by using tasks.

For example, I know how to delay a task but I dont really know how to set a timeout in seconds for a started task

Any suggestion?

Lorenzo
  • 29,081
  • 49
  • 125
  • 222

1 Answers1

1

You can easily implement a timeout like so:

public async Task TimoutReversal() {
    var timeout = TimeSpan.FromSeconds(10);
    try {
        //assumes HttpClient
        Client.Timeout = timeout;
        await Client.GetAsync(firstEndpoint);
    } catch (OperationCanceledException ex) {
        await Client.DeleteAsync(secondEndpoint);
    }
}

//or

public async Task TimoutReversal() {
    var timeout = TimeSpan.FromSeconds(10);
    var firstTask = Client.GetAsync(firstEndpoint);
    if (await Task.WhenAny(firstTask, Task.Delay(timeout)) == firstTask) {
        //success
    }else {
        //failure
        await Client.DeleteAsync(secondEndpoint);
    }
}

Also see protected answer here on SO: Task with timeout

Another option is to pass the Token from a CancellationTokenSource created from a TimeSpan to the HttpClient calls.

Community
  • 1
  • 1
JSteward
  • 6,833
  • 2
  • 21
  • 30