【实例简介】基于ORACLE的事件通知
【实例截图】
【核心代码】
using Oracle.DataAccess.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OracleDependency dep;
OracleConnection conn;
public Form1()
{
InitializeComponent();
//设置App的监听端口,即使用哪个端口接收Change Notification。
OracleDependency.Port = 49501;
string cs = "User Id = hiip; Password=hiip;Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.10.3)(PORT = 1521)))(CONNECT_DATA = (SERVICE_NAME = orcl)))";
conn = new OracleConnection(cs);
conn.Open();
}
//
private void btnReg_Click(object sender, EventArgs e)
{
if (dep == null || !dep.IsEnabled)
{
OracleCommand cmd = new OracleCommand("select * from userinfo", conn);
//绑定OracleDependency实例与OracleCommand实例
dep = new OracleDependency(cmd);
//指定Notification是object-based还是query-based,前者表示表(本例中为tab_cn)中任意数据变化时都会发出Notification;后者提供更细粒度的Notification,例如可以在前面的sql语句中加上where子句,从而指定Notification只针对查询结果里的数据,而不是全表。
//dep.QueryBasedNotification = false;
//dep.QueryBasedNotification = true;
//是否在Notification中包含变化数据对应的RowId
//dep.RowidInfo = OracleRowidInfo.Include;
//指定收到Notification后的事件处理方法
dep.OnChange = new OnChangeEventHandler(OnNotificaton);
//是否在一次Notification后立即移除此次注册
cmd.Notification.IsNotifiedOnce = false;
//此次注册的超时时间(秒),超过此时间,注册将被自动移除。0表示不超时。
cmd.Notification.Timeout = 0;
//False表示Notification将被存于内存中,True表示存于数据库中,选择True可以保证即便数据库重启之后,消息仍然不会丢失
cmd.Notification.IsPersistent = true;
//
cmd.ExecuteNonQuery();
//
rtb1.AppendText("Registration completed. " DateTime.Now.ToLongTimeString() Environment.NewLine);
}
}
private void btnUnreg_Click(object sender, EventArgs e)
{
//注销
if (dep.IsEnabled)
{
dep.RemoveRegistration(conn);
rtb1.AppendText("Registration Removed. " DateTime.Now.ToLongTimeString() Environment.NewLine);
}
}
private void OnNotificaton(object src, OracleNotificationEventArgs arg)
{
//可以从arg.Details中获得通知的具体信息,比如变化数据的RowId
DataTable dt = arg.Details;
//......
rtb1.BeginInvoke(
new Action(() =>
{
rtb1.AppendText("Notification Received. " DateTime.Now.ToLongTimeString() " Changed data(rowid): " arg.Details.Rows[0]["rowid"].ToString() Environment.NewLine);
}));
}
}
}