Home > OS >  How do I use timeout in C#
How do I use timeout in C#

Time:01-20

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;
    }
}

enter image description here

CodePudding user response:

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.

CodePudding user response:

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;
}
  • Related