1

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;
    }
}
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
  • 1
    please copy your code in the question, no need for snapshots in this case. If a database result takes 5 seconds to bring, there must be some optimization work that needs to be done. – Maytham Fahmi Jan 20 '23 at 11:14
  • Please provide enough code so others can better understand or reproduce the problem. – Community Jan 20 '23 at 11:16
  • 2
    Usually you would use a [CancellationToken](https://stackoverflow.com/questions/15067865/how-to-use-the-cancellationtoken-property) – Hans Kesting Jan 20 '23 at 11:17

2 Answers2

4

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.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
1

You can call WaitAsync on the the task produced by the call to Reports with a timeout. If the task completes then you can check the result, otherwise you can just return false.

private static async Task<bool> InformixTest()
{
    bool result;

    try
    {
        reportTask = _informixService.Reports("SELECT 1");
        await reportTask.WaitAsync(TimeSpan.FromSeconds(5));
        result = reportTask.Result != null;
    }
    catch (TimeoutException)
    {
        result = false;
    }

    return result;
}
YungDeiza
  • 3,128
  • 1
  • 7
  • 32