Как предотвратить повторное подключение БД при выходе из резьбы в. NET Core? - PullRequest
0 голосов
/ 23 января 2020

Моя цель - использовать пул потоков в максимально возможной степени при подключении к PostgreSQL 9.6 из .NET Core 3.1 через Npsql 4.1.2.

Когда я запускаю базовое c приложение, кажется, что поток выход, и соединение в пуле умирает (и новый открывается при следующем запросе). Это синхронизированные журналы запросов, которые указали мне на проблему. CONN - это сколько времени требуется, чтобы запустить await conn.OpenAsync(); и открыть соединение в MS. Журналы создаются путем нажатия на конечную точку каждые 5 секунд:

CONN: 670 QUERY: 30
CONN: 0 QUERY: 30
CONN: 0 QUERY: 35
CONN: 0 QUERY: 31
The thread 0x2b54 has exited with code 0 (0x0).
CONN: 911 QUERY: 32
CONN: 0 QUERY: 31
CONN: 0 QUERY: 39
CONN: 0 QUERY: 32
The thread 0x587c has exited with code 0 (0x0).
CONN: 842 QUERY: 35
CONN: 0 QUERY: 30
CONN: 0 QUERY: 42
The thread 0x79c8 has exited with code 0 (0x0).
CONN: 0 QUERY: 27

РЕДАКТИРОВАТЬ: На самом деле, при дальнейшем рассмотрении, я не уверен, что выход из потоков имеет какое-либо отношение к этому:

CONN: 817 QUERY: 26
CONN: 0 QUERY: 26
CONN: 0 QUERY: 27
CONN: 0 QUERY: 27
CONN: 1012 QUERY: 28
CONN: 0 QUERY: 38
CONN: 0 QUERY: 32
CONN: 0 QUERY: 28
The thread 0x58d8 has exited with code 0 (0x0).
CONN: 679 QUERY: 28
CONN: 0 QUERY: 35
CONN: 0 QUERY: 29
The thread 0x5224 has exited with code 0 (0x0).
CONN: 0 QUERY: 29
CONN: 774 QUERY: 29
CONN: 0 QUERY: 30
The thread 0x7130 has exited with code 0 (0x0).
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\3.1.1\Microsoft.AspNetCore.Http.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
CONN: 0 QUERY: 29
CONN: 0 QUERY: 40
The thread 0x6d74 has exited with code 0 (0x0).
CONN: 742 QUERY: 26
The thread 0x554 has exited with code 0 (0x0).
CONN: 0 QUERY: 26
CONN: 0 QUERY: 37
CONN: 0 QUERY: 27
The thread 0x5a44 has exited with code 0 (0x0).
CONN: 669 QUERY: 29
CONN: 0 QUERY: 38
CONN: 0 QUERY: 28
CONN: 0 QUERY: 28
CONN: 626 QUERY: 29
CONN: 0 QUERY: 31
The thread 0x6888 has exited with code 0 (0x0).
CONN: 0 QUERY: 36

Кажется, что Node не имеет этой проблемы вообще из коробки. Как мне повторно использовать соединение в C#?

PS Я столкнулся с этой проблемой 2 недели go и получил вознаграждение здесь , которое привело меня к созданию минимально воспроизводимый пример и сузьте проблему до выходящих потоков.

Это буквально весь мой код, который "минимально воспроизводим" из коробки на API fre sh. NET (создал час go в последней версии Visual Studio):

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Npgsql;
using System.Threading.Tasks;

namespace PostgresTestApp.Controllers
{
  [ApiController]
  [Route("[controller]")]
  public class PostgresTestController : ControllerBase
  {
    private readonly ILogger<PostgresTestController> _logger;

    public PostgresTestController(ILogger<PostgresTestController> logger)
    {
      _logger = logger;
    }

    [HttpGet]
    public async Task<int> Get()
    {
      var connString = "someConnectionString";

      int testNum = 100;

      await using var conn = new NpgsqlConnection(connString);
      var connTimer = System.Diagnostics.Stopwatch.StartNew(); // TODO: Remove this testing line
      await conn.OpenAsync();
      connTimer.Stop(); // TODO: Remove this testing line
      var msToConnect = connTimer.ElapsedMilliseconds; // TODO: Remove this testing line

      var jobsQueryTimer = System.Diagnostics.Stopwatch.StartNew(); // TODO: Remove this testing line0
      await using (var cmd = new NpgsqlCommand("SELECT 1", conn))
      await using (var reader = await cmd.ExecuteReaderAsync())
        while (await reader.ReadAsync()) {
          testNum = reader.GetInt32(0);
        }
      jobsQueryTimer.Stop(); // TODO: Remove this testing line
      var msToQuery = jobsQueryTimer.ElapsedMilliseconds; // TODO: Remove this testing line

      System.Diagnostics.Debug.WriteLine($"CONN: {msToConnect} QUERY: {msToQuery}");

      return testNum;
    }
  }
}
...