无法在Npgsql中立即收到多个通知

今天我编写了以下代码,该代码适用于名为Npgsql的PostgreSQL C#库:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Npgsql; namespace PostgreSQLNotificationsTest { class Program { static void Main(string[] args) { using (var conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=my_password;Database=helper_db.psql;SyncNotification=true")) { conn.Notification += OnNotification; conn.Open(); using (var command = new NpgsqlCommand("listen notifytest;", conn)) { command.ExecuteNonQuery(); } Console.ReadLine(); }; } private static void OnNotification(object sender, NpgsqlNotificationEventArgs e) { Console.WriteLine("event handled: " + e.AdditionalInformation); } } } 

然后我做以下

createdb.exe -h 127.0.0.1 -p 5432 -U postgres -W helper_db.psql

psql.exe -h 127.0.0.1 -p 5432 -U postgres -W helper_db.psql

create table helper(第一个文本主键,第二个整数);

 CREATE OR REPLACE FUNCTION nf() RETURNS TRIGGER AS $$ BEGIN PERFORM pg_notify('notifytest', format('INSERT %s %s', NEW.first, NEW.second)); RETURN NULL; END; $$ LANGUAGE plpgsql; CREATE TRIGGER any_after AFTER INSERT OR UPDATE OR DELETE ON helper FOR EACH ROW EXECUTE PROCEDURE nf(); 

插入辅助值(’first’,10),(’second’,20);

在C#项目中,我得到以下输出:

事件处理:先插入10

没有“事件处理:插入第二个20”。 只有当我执行下一个操作,如“从帮助程序中删除”时,我才会收到它。

为什么?

除非您的客户端库支持检查网络套接字是否有缓冲数据,否则接收通知的唯一方法是触发套接字上的其他活动。

许多应用程序会定期发送一个空查询字符串( "" )来执行此操作。

如果客户端库支持它并且您没有使用SSL,则可以定期在连接上调用某种checkForNotifications()函数。 这在PgJDBC中是可能的,但我不知道nPgSQL,所以我只能建议你查看文档。

更新(2015-02-27):这个bug已经在github上的master分支中修复了。 请注意,master分支是我们即将推出的3.0版本,可能会有一些我们正在处理的错误。 请试一试,让我知道它是否适合您。

这是Npgsql中的一个错误。 我们正在努力解决它。 检查此拉取请求以获取更多信息: https : //github.com/franciscojunior/Npgsql2/pull/46 in special commit: https : //github.com/glenebob/Npgsql2/commit/98fd469048a20119755777ce3a8ffc4397f4a114

但我们正在尝试另一种方法来解决这个问题。 请注意,只有在很短的时间内发送多个通知时才会出现此问题。 如果您在通知之间保留1或2秒的空间,则会正确传递它们。

一旦我们得到修复,我会在这里更新我的答案。

很抱歉这个问题可能造成的不便。