我正在嘗試使用SqlDependency類監視數據庫表中的更改。雖然我一定錯過了一些東西。我已經遵循了我在網上看到的所有例子,並且已經查看了本網站上的所有問題。我只是看不到我缺少的東西。以下是我在數據庫上運行的初始命令,以啓用服務代理並創建隊列和服務。Windows服務中的SqlDependency未觸發
CREATE QUEUE ScheduleChangeQueue
GO
CREATE SERVICE ScheduleChangeService ON QUEUE ScheduleChangeQueue ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification])
GO
ALTER DATABASE [database] SET ENABLE_BROKER
在C#方面,我創建了一個類,它具有一個被調用來啓動進程的靜態設置方法。下面是該代碼:
public class SqlDependencyManager
{
private static bool DoesUserHavePermission()
{
var success = false;
try
{
Program.Log.Info("Retrieving SqlPermission to establish dependency...");
var clientPermission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
// this will throw an error if the user does not have the permissions
clientPermission.Demand();
success = true;
Program.Log.Info("SqlPermission established. Continue setting up dependency.");
}
catch (Exception ex)
{
Program.Log.Error(ex, "SqlPermission not able to be established.");
}
return success;
}
public static void Setup()
{
if (!DoesUserHavePermission())
{
return;
}
var connectionString = ConfigurationManager.ConnectionStrings["ShowMakerPro"].ConnectionString;
// You must stop the dependency before starting a new one.
// You must start the dependency when creating a new one.
SqlDependency.Stop(connectionString);
SqlDependency.Start(connectionString);
using (var cn = new SqlConnection(connectionString))
{
using (var cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
//cmd.CommandText = "SELECT MAX(LastChangeTime) FROM Schedule WHERE ChannelID IN (SELECT ID FROM Channels WHERE Type = 1) AND StartTime BETWEEN (GETDATE() - 7) AND (GETDATE() + 30)";
cmd.CommandText = "SELECT LastChangeTime FROM dbo.Schedule";
cmd.Notification = null;
// Creates a new dependency for the SqlCommand. Then creates attaches handler for the notification of data changes
new SqlDependency(cmd).OnChange += SqlDependency_OnChange;
cn.Open();
cmd.ExecuteReader();
}
}
Program.Log.Info("SQL Dependency set. Now monitoring schedule table for changes.");
}
private static void SqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
// this will remove the event handler since the dependency is only for a single notification
((SqlDependency)sender).OnChange -= SqlDependency_OnChange;
ScheduleOutputterService.BuildSchedules();
Program.Log.Info("SQL Dependency triggered schedule rebuild. Resetting SqlDependency to monitor for changes.");
Setup();
}
}
}
我看到的代碼獲取設置OK和方法的OnChange針對訂閱燒製一次,但後來我再也看不到它開火之後。我手動進入數據庫,並更改LastChangeTime字段,希望它會強制事件觸發,但沒有任何反應。
有人可以澄清我在哪裏搞砸嗎?我看到一些人在線上表示,這在Windows窗體中工作正常,但在服務中也存在一些問題。
你在你的OnChange此評論:'//因爲依賴是僅適用於單個notification'也許這是原因,這將消除事件處理程序? – Serg
@Serg這是必需的,因爲每次事件觸發它都會破壞依賴關係。您必須每次重新創建它以便在隨後的更改中繼續觸發它。 – spinon
所以也許娛樂不起作用?對不起,如果我誤解你的代碼。 – Serg