Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
NpgsqlでNotifyを受信するサンプル
using System;
using Npgsql;
namespace ConsoleGetNotify
{
class Program
{
static void Main( string[] args )
{
Program program = new Program();
program.listenSample();
}
private void listenSample()
{
NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder();
builder.Add( "Server", "192.168.223.130" );
builder.Add( "Port", 5432 );
builder.Add( "User Id", "postgres" );
builder.Add( "Password", "***" );
builder.Add( "Database", "postgres" );
try
{
Console.Out.WriteLine( "Create Connection Instance." );
using ( NpgsqlConnection listenConnection = new NpgsqlConnection( builder.ConnectionString ) )
{
Console.Out.WriteLine( "Try Connection Open..." );
listenConnection.Open();
Console.Out.WriteLine( "Connection Open!" );
listenConnection.Notification += ( sender, e ) =>
{
Console.Out.WriteLine( "Recieve NOTIFY!" );
string message = $"Notify:{e.Condition}, AdditionalData={e.AdditionalInformation}";
Console.Out.WriteLine( message );
};
Console.Out.WriteLine( "Execute LISTEN Command." );
using ( NpgsqlCommand command = new NpgsqlCommand( "LISTEN test;", listenConnection ) )
{
command.ExecuteNonQuery();
}
Console.Out.WriteLine( "Wait NOTIFY..." );
listenConnection.Wait();
}
}
catch ( Exception ex )
{
Console.Error.WriteLine( ex.ToString() );
}
finally
{
Console.Out.WriteLine( "続行するには何かキーを押してください . . ." );
Console.ReadKey();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment