Search code examples
c#.netasp.net-coreasp.net-web-api

How do I use timeout in C#


I want it to return false if no value is returned within 5 seconds.

I couldn't find how to, here is my code:

public async Task<bool> InformixTest()
{
    string query = await _informixService.Reports("SELECT 1");

    if (query != null)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Solution

  • You can use CancellationTokenSource.CancelAfter and pass 5000 (5 seconds). Here is a link with the simple example at Microsoft doc.

    That said if I have a query that takes 5 seconds, I would also check if my query is optimized and do the job correctly.