当我 SetCommandTimeout 时遇到问题,就像该方法无法正常工作一样。
我使用 PostgreSQL 作为数据库,对于 EntityFramework Core,我使用 Npgsql.EntityFrameworkCore.PostgreSQL
版本 5.0.5.1
在代码中,我将超时设置为 1 秒,就像这样 context.Database.SetCommandTimeout(1);
我设置了一个秒表来检查它花费了多少时间,但是 ElapsedMiliseconds 总是返回大约 15000 毫秒到16000 毫秒。所以 SetCommandTimeout(1)
显然不起作用。
我也尝试过使用 context.Database.SetCommandTimeout(TimeSpan.FromSeconds(1));
也不起作用。
还有一件事,我只想为特定请求设置超时。所以另一个请求将有默认超时。
这是我的代码:
[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
}
}
}
这是我在 Startup.Cs 中注册它的方式
services.AddDbContext<DatabaseContext>(options =>
{
options.UseNpgsql(ConnectionString);
});
我是不是漏了什么?
提前致谢
最佳答案
命令超时是允许在数据库服务器上执行查询/命令的时间。计时器在数据库服务器收到请求时启动。由于网络吞吐量或其他限制(包括网络服务器上的资源耗尽),您的端到端往返时间可能比命令超时时间长。
Command Timeout: The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error. Source
关于c# - SetCommandTimeout 的执行不适用于 PostgreSQL 的 EF Core 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70859494/