NpgsqlConnection 和 OpenAsync() 方法导致 NullReferenceExeption

NpgsqlConnection and OpenAsync() method causing NullReferenceExeption

最近我在与 CentOS 8 上托管的 PostgreSQL 13 数据库通信时偶然发现了某些问题。我无法使用 NpgsqlConnection class 中的方法 OpenAsync() 打开连接。同步 Open() 方法可以正常工作,并允许我创建和使用连接。 我希望也许有人偶然发现了类似的问题。 预先感谢您的帮助!

示例代码:

             [Fact]
        public async Task TestDatabaseConnection()
        {
            NpgsqlLogManager.Provider = new NLogLoggingProvider();
            NpgsqlLogManager.IsParameterLoggingEnabled = true;
            Npgsql.NpgsqlConnection con = new Npgsql.NpgsqlConnection("Server=xxx;Database=xxx;User Id=xxx;Password=xxx");
            try
            {
                //con.Open(); works ok
                await con.OpenAsync(); //cause error
            }
            catch (Exception exc)
            {
                Console.WriteLine("test " + exc);
            }
        }

日志:

Opening connection...
Opening connection...
Attempting to connect to [x:x:x:x::x]:5432
Exception thrown: 'System.TimeoutException' in Npgsql.dll
Exception thrown: 'System.TimeoutException' in System.Private.CoreLib.dll
Failed to connect to [x:x:x:x::x]:5432
Exception thrown: 'System.ObjectDisposedException' in System.Net.Sockets.dll
Attempting to connect to x.x.x.x:5432
Exception thrown: 'System.TimeoutException' in Npgsql.dll
Exception thrown: 'System.ObjectDisposedException' in System.Private.CoreLib.dll
Exception thrown: 'System.TimeoutException' in System.Private.CoreLib.dll
Failed to connect to x.x.x.x:5432
Exception thrown: 'Npgsql.NpgsqlException' in Npgsql.dll
Exception thrown: 'Npgsql.NpgsqlException' in System.Private.CoreLib.dll
Exception thrown: 'Npgsql.NpgsqlException' in Npgsql.dll
Exception thrown: 'Npgsql.NpgsqlException' in System.Private.CoreLib.dll
Breaking connector
Cleaning up connector
Exception thrown: 'System.NullReferenceException' in Npgsql.dll
Object reference not set to an instance of an object.

我们设法找到了解决方案。在连接字符串中添加 Timeout 参数应该就足够了。由于某种原因,建立连接需要很长时间。其原因仍在调查中。打开连接平均需要 21 秒 - 但更高的超时参数可以保护我们免受异常影响。

示例:

Server=xxx;Database=yyy;User Id=bbb;Password=aaa;Timeout=100

关于这个问题的进一步讨论可以在这里找到: https://github.com/npgsql/npgsql/issues/3295