Skip to content

Instantly share code, notes, and snippets.

@monakaice
Last active March 28, 2017 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monakaice/53d962735c0b64839f84ca31d602c07c to your computer and use it in GitHub Desktop.
Save monakaice/53d962735c0b64839f84ca31d602c07c to your computer and use it in GitHub Desktop.
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