我已经设法让 SqlDependency 工作,但只要我不使用IsolationLevel.ReadUncommited
我认为与 SqlDependency 无关的 SQL 事务。
当我IsolationLevel.ReadUncommitted
在事务中使用(下面有大量评论)时,SqlDependency 订阅失败,并立即OnChange
通知:
sqlNotificationEventArgs.Info = "Isolation";
sqlNotificationEventArgs.Source = "Statement";
sqlNotificationEventArgs.Type = "Subscribe";
当我删除 IsolationLevel 时,一切都按预期工作(当然,隔离是不正确的)。
这是我的相关代码:
private static string connString = "the connection string";
[MTAThread]
private static void Main(string[] args)
while(true)
{
using (var context = new LinqDataContext(connString))
{
var conn = context.Connection;
conn.Open();
/***********************************************************************/
/* Remove `IsolationLevel.ReadUncommitted` and the SqlDependency works */
/***********************************************************************/
using (var trans = conn.BeginTransaction(IsolationLevel.ReadUncommitted))
{
// simplified query, the real query uses UPDATE OUTPUT INSERTED
const string sqlCommand = "SELECT [Columns] FROM dbo.[TABLE] WHERE [Status] = 'ready'";
results = conn.Query({transaction: trans, sql: sqlCommand});
trans.Commit();
}
DoAwesomeStuffWithTheResults(results, context);
}
WaitForWork();
}
}
SqlDependency 相关代码:
private static ManualResetEvent _quitEvent = new ManualResetEvent(false);
/// <summary>
/// Sets up a SqlDependency a doesn't return until it receives a Change notification
/// </summary>
private static void WaitForWork(){
// in case we have dependency running we need to go a head and stop it first.
SqlDependency.Stop(connString);
SqlDependency.Start(connString);
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand("SELECT [Status] From dbo.[TABLE]", conn))
{
cmd.Notification = null;
var dependency = new SqlDependency(cmd);
dependency.OnChange += dependency_OnDataChangedDelegate;
conn.Open();
cmd.ExecuteReader();
}
}
_quitEvent.WaitOne();
SqlDependency.Stop(connString);
}
private static void dependency_OnDataChangedDelegate(object sender, SqlNotificationEventArgs e)
{
((SqlDependency)sender).OnChange -= dependency_OnDataChangedDelegate;
_quitEvent.Set();
}
我觉得好像我已经正确处理了上下文、它的连接和事务——在设置 SqlDependency 之前,但似乎情况并非如此。
我在这里做错了什么?