gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:30:27 30 4
gpt4 key购买 nike

最近,我在与托管在 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com