Start learning free

LESSON 105 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Don't Wait Forever in C#

Practice

A service can also be slow instead of broken: overloaded, it answers after many seconds, or never. http.GetAsync waits up to 100 seconds, HttpClient's default, and so does your customer, while your shop holds the request open for nothing.

Give the call a timeout: pass new CancellationTokenSource(1000).Token as the second argument of GetAsync, and the call is cancelled after 1000 milliseconds. Cancelling throws a TaskCanceledException, which would crash the route. Catch it with try and catch: the catch block runs only when the code inside try threw that exception, and is skipped otherwise. Declare the response above the try, so the code below it can use it. Here it is in a weather app:

HttpResponseMessage response;
try {
    response = await http.GetAsync(WEATHER + "/today/" + name, new CancellationTokenSource(2000).Token);
} catch (TaskCanceledException) {
    return Results.Json(new { error = "The weather service took too long" }, statusCode: 504);
}

The status is 504 Gateway Timeout: like 502, the problem is behind your shop, and 504 says exactly what it was. The customer waits one second at most, and gets an answer either way.

The check makes the supplier take 2 seconds for one request with POST /check/supplier-slow, a page that only exists in the tests. Your shop must answer:

GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-slow {"times": 1}  →  200  {"slow_next": 1}
GET /products/1/supplier-stock  →  504  {"error": "The supplier took too long"}
GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1}  →  200  {"down_next": 1}
GET /products/3/supplier-stock  →  502  {"error": "The supplier is not answering"}
GET /products/6/supplier-stock  →  404  {"error": "The supplier doesn't sell this product"}

Your task: in the /products/{id}/supplier-stock route, declare HttpResponseMessage response;, send the request to the supplier inside a try block with a 1000 ms CancellationTokenSource token, catch TaskCanceledException, and answer "The supplier took too long" with 504. The 404 and 502 checks stay below, unchanged.


Assignment
Follow the Coding Tutorial to give the supplier call a time limit and answer 504 when it runs out.


Hint
Inside the try, write response = ... without var: the variable already exists. The catch must return, or C# says response may be unassigned below it.


STEP 1 OF 5
    Ctrl + Enter to check

    Svc Timeouts in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free