Last active
March 28, 2017 03:30
-
-
Save monakaice/53d962735c0b64839f84ca31d602c07c to your computer and use it in GitHub Desktop.
NpgsqlでNotifyを受信するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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