Is there some broader approach to querying the database that could guarantee either completion or an error in a certain time, say 20 seconds?
Yes, there is. There is a broader approach to performing asynchronous IO that guarantees completion or error in a specified time.
In C#, one can create CancellationToken
s that are cancelled after a given time span. Most async
methods accept a CancellationToken
. IDbConnection.QueryAsync
is no exception.
You create a cancellation token source, which takes an optional argument specifying the delay before the task is cancelled (as a TimeSpan
or int
See example:
try
{
IDbConnection db = ...;
var cts = new CancellationTokenSource(10_000);
var cmd = new CommandDefinition(commandText: "your query", cancellationToken: cts.Token);
await db.QueryAsync<Foo>(cmd);
// Success.
}
catch (TaskCanceledException e)
{
// Failure due to timeout.
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…