this MSDN page에서 예제를 가져 와서 그대로 사용했습니다. 코드를 실행하면 올바르게 컴파일되지만 changeCount
은 실제로 반환 된 데이터가 변경되었는지 여부에 관계없이 끝없이 증가합니다. 실제로 의 변경 내용이 인 경우 dataGridView1
에 변경 사항이 올바르게 반영됩니다. 내 SqlDependency
이 변경되지 않은 것처럼 보이지만 반복적으로 실행되는 것처럼 보이는 이유는 무엇입니까?SqlDependency를 사용하면 지속적인 업데이트가 발생합니다.
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
#endregion
namespace PreAllocation_Check
{
public partial class Form1 : Form
{
int changeCount = 0;
const string tableName = "MoxyPosition";
const string statusMessage = "Last: {0} - {1} changes.";
DataSet dataToWatch = null;
SqlConnection MoxyConn = null;
SqlCommand SQLComm = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (CanRequestNotifications())
{
SqlDependency.Start(GetConnectionString());
if (MoxyConn == null)
MoxyConn = new SqlConnection(GetConnectionString());
if (SQLComm == null)
{
SQLComm = new SqlCommand(GetSQL(), MoxyConn);
SqlParameter prm = new SqlParameter("@Quantity", SqlDbType.Int);
prm.Direction = ParameterDirection.Input;
prm.DbType = DbType.Int32;
prm.Value = 100;
SQLComm.Parameters.Add(prm);
}
if (dataToWatch == null)
dataToWatch = new DataSet();
GetData();
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
SqlDependency.Stop(GetConnectionString());
if (MoxyConn != null)
MoxyConn.Close();
}
private bool CanRequestNotifications()
{
try
{
SqlClientPermission SQLPerm = new SqlClientPermission(PermissionState.Unrestricted);
SQLPerm.Demand();
return true;
}
catch
{
return false;
}
}
private string GetConnectionString()
{
return "server=***;database=***;user id=***;password=***";
}
private void GetData()
{
dataToWatch.Clear();
SQLComm.Notification = null;
SqlDependency SQLDep = new SqlDependency(SQLComm);
SQLDep.OnChange += new OnChangeEventHandler(SQLDep_OnChange);
using (SqlDataAdapter adapter = new SqlDataAdapter(SQLComm))
{
adapter.Fill(dataToWatch, tableName);
dataGridView1.DataSource = dataToWatch;
dataGridView1.DataMember = tableName;
}
}
private string GetSQL()
{
return "SELECT PortID, CONVERT(money, SUM(PreAllocPos), 1) AS PreAllocation, CONVERT(money, SUM(AllocPos), 1) AS Allocation, CONVERT(money, SUM(PreAllocPos) - SUM(AllocPos), 1) AS PreLessAlloc " +
"FROM MoxyPosition " +
"WHERE CONVERT(money, PreAllocPos, 1) <> CONVERT(money, AllocPos, 1) " +
"GROUP BY PortID " +
"ORDER BY PortID ASC;";
}
void SQLDep_OnChange(object sender, SqlNotificationEventArgs e)
{
ISynchronizeInvoke i = (ISynchronizeInvoke)this;
if (i.InvokeRequired)
{
OnChangeEventHandler tempDelegate = new OnChangeEventHandler(SQLDep_OnChange);
object[] args = { sender, e };
i.BeginInvoke(tempDelegate, args);
return;
}
SqlDependency SQLDep = (SqlDependency)sender;
SQLDep.OnChange -= SQLDep_OnChange;
changeCount++;
DateTime LastRefresh = System.DateTime.Now;
label1.Text = String.Format(statusMessage, LastRefresh.TimeOfDay, changeCount);
GetData();
}
}
}
편집 : 여기
소스의 데이타베이스가 나는 현재 브로커 서비스가 활성화되지 않습니다이에 대한 실행하려는 것을 주목할 필요가, 그래서 내가 백업 내 코드를 테스트하기 위해 내 새 이름으로 복원 한 다음ALTER DATABASE my_db_name SET ENABLE_BROKER
을 실행했습니다. 내 테스트는 모두이 대체 데이터베이스에 있었고, 이는 내가 유일한 사용자임을 의미합니다.
고마워요! 이 답변으로 지금은 약 2 일 동안 검색 및 시도에서 벗어났습니다. –