0
數據庫表(DummyData)具有單列(Message)並且只有一個記錄/行的值爲「hello」。我使用signalR在網頁上顯示此值。只要此值在數據庫中更新,網頁上的文本也會更新而不刷新。所有這些工作正常。SignalR正在擊中數據庫兩次
我看到的問題是,該應用程序擊中數據庫兩次。這是由設計還是錯誤的代碼。 (頁面被打開一次。沒有任何其他情況下)
ASPX
<script>
$(function() {
var notify = $.connection.notificationsHub;
$.connection.hub.start().done(function() {
notify.server.notifyAllClients();
});
notify.client.displayNotification = function (msg) {
$("#newData").html(msg);
};
});
</script>
<span id="newData"></span>
aspx.cs
public string SendNotifications()
{
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [Message] FROM [dbo].[DummyData]";
SqlCommand command = new SqlCommand(query, connection)
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
return message;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
NotificationsHub obj = new NotificationsHub();
obj.NotifyAllClients();
}
}
NotificationsHub.cs
public class NotificationsHub : Hub
{
Messages obj = new Messages();
public void NotifyAllClients()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.displayNotification(obj.SendNotifications());
}
public override Task OnConnected()
{
NotifyAllClients();
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
NotifyAllClients();
return base.OnDisconnected(stopCalled);
}
}
這裏是斷點如何打在調試:
在頁面加載:
- OnConnected()
- NotifyAllClients()
- SendNotifications()
- NotifyAllClients()
//why is this hit again
- Send通知()
當我運行
update DummyData Set Message='helloworld'
- dependency_OnChange()
- NotifyAllClients()
- SendNotifications()
- dependency_OnChange()
//hit a second time here too
- NotifyAllClients()
- SendNotifications()
請問能否請教,如何防止第二次打 – Qwerty
留下兩個電話中的哪一個,其實並不重要。 – rdoubleui