简体   繁体   English

C#将侦听器附加到Npgsql连接

[英]C# attach listener to a Npgsql connection

I'm building an app in C# that use npgsql connection for queries in postgres database. 我正在用C#构建一个使用npgsql连接在postgres数据库中查询的应用程序。 I want to know if there is a way to be notified at all steps of query execution; 我想知道是否有一种方法可以在查询执行的所有步骤中得到通知; I mean i want to receive messages : 我的意思是我想接收消息:

  • "open" : when connection is open “打开”:连接打开时
  • "connecting" : when connection is connecting “ connecting”:连接正在连接时
  • "executing" : when connection is executing “正在执行”:执行连接时
  • "close" : when query is executed and connection closed “ close”:执行查询并关闭连接时

Is there a way to do that ? 有没有办法做到这一点 ?

You can do this, but you have to trigger the notifications yourself. 您可以执行此操作,但是您必须自己触发通知。 It is doable and even easy. 这是可行的,甚至很容易。 In ADO.NET you have code flow similar to: 在ADO.NET中,您具有类似于以下内容的代码流:

DbProviderFactory factory = DbProviderFactories.GetFactory("Npgsql");
using(DbConnection con = factory.CreateConnection()) 
{
      con.ConnectionString = ConfigurationManager.AppSettings[connectionName];
      con.Open();  
      // Connection is open, notify user
      DbCommand cmd = connection.CreateCommand();
      cmd.CommandText = query; 

      // Query execution is going to start, add code to inform user
      cmd.ExecuteXXX();
      // Query execution is done, add code to inform user
}

// the connection is closed - notify user

Notifications should be asynchronous to avoid blocking the database code you can implement them with events. 通知应该是异步的,以避免阻塞数据库代码,您可以使用事件来实现它们。

Are you looking to trap the StateChange event? 您是否要捕获StateChange事件? Hope this will point you at the right direction. 希望这会为您指明正确的方向。

    Dim csb = New NpgsqlConnectionStringBuilder(GetConnectionString(connectionName))
    csb.CommandTimeout = 0
    Using connection = New NpgsqlConnection(csb.ConnectionString)
        AddHandler connection.StateChange, AddressOf myHandler  ' <== This is where you specify the event Handler
        Using transaction = connection.BeginTransaction()
            ' Do your thing here.
            transaction.Commit()
        End Using
    End Using
End Sub


' This function will get called whenever the connection state changes.
Private Function myHandler(sender As Object, e As StateChangeEventArgs) As Object
    ' Do something here
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM