Cancel HttpClient on azure function in case the operation takes longer than x minutes

Tes Gam 81 Reputation points
2020-12-18T01:14:44.69+00:00

I have an azure function which has been called every 5minutes. The function takes less than a min to respond but sometimes took longer than normal and causes some logical issues in my app. How can I cancel the request if takes more than x min (e.g. 4min)?

var response = await client.GetStringAsync()
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,262 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,245 questions
0 comments No comments
{count} votes

Accepted answer
  1. YASER SHADMEHR 781 Reputation points
    2020-12-18T01:21:10.053+00:00

    You have two choices:

    1. Set timeout for your HttpClient

    client.Timeout = TimeSpan.FromMinutes(4);
    
    try
    {
        var response = await client.GetStringAsync();
    }
    catch (TaskCanceledException)
    {
        // your logic when timeout happens
    }
    

    2. Cancel async task

    var cts = new CancellationTokenSource()
    cts.CancelAfter(4 * 60 * 1000);
    
    try
    {
        var response = await client.GetStringAsync(uri, cts.Token);
    }
    catch (TaskCanceledException)
    {
         // your logic when timeout happens
    }
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful