Subskrypcja SqlDependency nie działa przy użyciu IsolationLevel.ReadUn zatwierdzone w (niepowiązane?) Transakcja
Udało mi się uzyskać działanie SqlDependency, ale tylko tak długo, jak nie używamIsolationLevel.ReadUncommited
w tym, co uważałem za transakcję SQL niezwiązaną z SqlDependency.
Kiedy używamIsolationLevel.ReadUncommitted
w transakcji (mocno skomentowane poniżej) subskrypcja SqlDependency kończy się niepowodzeniem z natychmiastowymOnChange
powiadomienie o:
sqlNotificationEventArgs.Info = "Isolation";
sqlNotificationEventArgs.Source = "Statement";
sqlNotificationEventArgs.Type = "Subscribe";
Gdy usuwam poziom izolacji, wszystko działa zgodnie z oczekiwaniami (oczywiście izolacja nie jest oczywiście prawidłowa).
Oto mój odpowiedni kod:
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();
}
}
Kod związany z zależnością Sql:
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();
}
Czuję się tak, jakbym właściwie pozbył się kontekstu, jego połączenia i transakcji - przed skonfigurowaniem SqlDependency, ale wydaje się, że tak nie jest.
Co ja tu robię źle?