I have a problem when I SetCommandTimeout is like the method is not working properly.
I Use PostgreSQL as database, and for the EntityFramework Core I'm using Npgsql.EntityFrameworkCore.PostgreSQL
with Version 5.0.5.1
In the code I Set Timeout for 1s like this context.Database.SetCommandTimeout(1);
and I set a Stopwatch to check how much time it takes, but the ElapsedMiliseconds always return around 15000ms to 16000ms. so the SetCommandTimeout(1)
is clearly not working.
I also tried using context.Database.SetCommandTimeout(TimeSpan.FromSeconds(1));
is not working either.
One more thing, I only want to Set Timeout for specific Request. So the other Request will have the default timeout.
Here's my code:
[Route("api/[controller]")]
[ApiController]
public class TestController : Controller
{
private readonly DatabaseContext context;
public TestController(DatabaseContext context)
{
this.context = context;
}
[AllowAnonymous]
[HttpGet]
public async Task<IActionResult> Test()
{
var sw = Stopwatch.StartNew();
try
{
context.Database.SetCommandTimeout(1);
var test = await context.Test.FirstOrDefaultAsync();
return Ok();
}
catch (Exception)
{
return BadRequest();
}
finally
{
sw.Stop();
var elapsed = sw.ElapsedMilliseconds; // always return around 15000ms to 16000ms
}
}
}
here's how I register it in Startup.Cs
services.AddDbContext<DatabaseContext>(options =>
{
options.UseNpgsql(ConnectionString);
});
did I missing something?
Thanks in advance
The command timeout is the time a query / command is allowed to execute on the database server. The timer starts when the database server receives the request. Your end-to-end round trip time may be higher than the command timeout due to network throughput or other constraints - including resource exhaustion on your web server.
Command Timeout: The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error. Source