c# - NpgsqlConnection 和 OpenAsync() 方法导致 NullReferenceExeption

标签 c# postgresql centos npgsql

最近,我在与托管在 CentOS 8 上的 PostgreSQL 13 数据库通信时偶然发现了某些问题。我无法使用 NpgsqlConnection 类中的方法 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 秒 - 但更高的 Timeout 参数可以保护我们免受异常影响。
例子:

Server=xxx;Database=yyy;User Id=bbb;Password=aaa;Timeout=100
可以在此处找到有关此问题的进一步讨论:
https://github.com/npgsql/npgsql/issues/3295

关于c# - NpgsqlConnection 和 OpenAsync() 方法导致 NullReferenceExeption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64626528/

相关文章:

c# - Azure 服务总线消息泵真的是事件驱动的吗?

c# - Mono for Android 中的自定义应用程序子类

ruby-on-rails - 问题将数据库迁移到 Heroku - PG::UndefinedTable: ERROR: relation "users"does not exist

bash - 遍历 Ubuntu 16 中的文件夹文件

ruby-on-rails - 在 Windows、CentOS 和 Mint 上安装 Ruby on Rails 时出错

c# - 任何内置 object.AsType<T>

C#:从列表中选择特定索引值

linux - Systemd 重新加载进程被杀死

C# Entity Framework Core 使用 native 枚举数据类型存储枚举

java - Postgres 异常和 java