C# 是否与Npgsql并行.For?
是否可以将Npgsql函数与块一起使用 这是我的示例,但出现异常“后端发送了无法识别的响应类型:\0” 和PostgreSql表模式C# 是否与Npgsql并行.For?,c#,postgresql,parallel-processing,npgsql,C#,Postgresql,Parallel Processing,Npgsql,是否可以将Npgsql函数与块一起使用 这是我的示例,但出现异常“后端发送了无法识别的响应类型:\0” 和PostgreSql表模式 -- Table: paralleltest -- DROP TABLE paralleltest; CREATE TABLE paralleltest ( id integer ) WITH ( OIDS=TRUE ); GRANT ALL ON TABLE paralleltest TO public; 克里斯蒂安 Npgsql和其他提供程序一样
-- Table: paralleltest
-- DROP TABLE paralleltest;
CREATE TABLE paralleltest
(
id integer
)
WITH (
OIDS=TRUE
);
GRANT ALL ON TABLE paralleltest TO public;
克里斯蒂安
Npgsql和其他提供程序一样,不是线程安全的。由于使用具有相同连接的多个线程,最终会出现此问题
为了使其工作,您必须将创建连接的线路放在并联回路内。对于回路:
string SqlParallel = "";
int OID = -1;
Parallel.For(0, 100, i =>
{
using (NpgsqlConnection PGconnexion = new NpgsqlConnection(...))
{
SqlParallel = string.Format(@"INSERT INTO ParallelTest(Id) VALUES({0}) RETURNING OID;", i);
using (NpgsqlCommand PGcommandParallel = new NpgsqlCommand(SqlParallel, PGconnexion))
{
try { OID = (int)PGcommandParallel.ExecuteScalar(); }
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
Console.WriteLine("Insert: {0} OID: {1}", i, OID);
}
});
我在这里测试了一下,效果不错。请尝试一下,如果您对此更改仍有问题,请告诉我。
请注意,我使用了“using”子句,以便在块完成后立即关闭连接
我希望它能有所帮助。在Francisco Junior的帮助下,这里是线程安全解决方案
Parallel.For(0, 100, i =>
{
string SqlParallel = string.Format(@"INSERT INTO ParallelTest(Id) VALUES({0}) RETURNING OID;", i);
using (NpgsqlConnection PGconnexionParallel = new NpgsqlConnection(string.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};", PGHost, PGPort, PGUser, PGPassword, PGDatabase)))
{
PGconnexionParallel.Open();
using (NpgsqlCommand PGcommandParallel = new NpgsqlCommand(SqlParallel, PGconnexionParallel))
{
try
{
int OID = (int)PGcommandParallel.ExecuteScalar();
Console.WriteLine("SqlParallel: {0} OID: {1}", SqlParallel, OID);
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
}
});
这个解决方案的问题在于,它不是做事情的最佳实践方式。在这里,我们在代码中“新建”一个NpgsqlConnection,而不是使用依赖项注入进行设置。
Parallel.For(0, 100, i =>
{
string SqlParallel = string.Format(@"INSERT INTO ParallelTest(Id) VALUES({0}) RETURNING OID;", i);
using (NpgsqlConnection PGconnexionParallel = new NpgsqlConnection(string.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};", PGHost, PGPort, PGUser, PGPassword, PGDatabase)))
{
PGconnexionParallel.Open();
using (NpgsqlCommand PGcommandParallel = new NpgsqlCommand(SqlParallel, PGconnexionParallel))
{
try
{
int OID = (int)PGcommandParallel.ExecuteScalar();
Console.WriteLine("SqlParallel: {0} OID: {1}", SqlParallel, OID);
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
}
});