c# - SetCommandTimeout 的执行不适用于 PostgreSQL 的 EF Core 5

标签 c# entity-framework-core npgsql

当我 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/

相关文章:

entity-framework-4 - 如何通过连接使用Entity Framework + PostgreSQL?

c# - 使用 A* 并仍然避免碰撞?

c# - 我可以在 VSIX 中检测到使用 Visual Studio Workspace 保存(未更改)的文档吗?

c# - 在 .Net Core 2.0 + SQLite EFCore 中,并发检查不适用于 'delete'

c# - 如何从 Dotnet EF 中删除唯一索引?

c# - npgsql 泄漏 Postgres 数据库连接 : Way to monitor connections?

c# - 使用安装项目安装时指定 Windows 服务名称

c# - 在 .net 核心中使用多个结果集

asp.net-core - Asp.Net 核心 2.0 : Detect Startup class invoked from migration or other ef operation

postgresql - RavenDB Sql 复制和 Postgres uuid