2016-08-17 3 views
0

vs2013 및 .net framwork 4.5.1과 함께 asp.net mvc 응용 프로그램을 가지고 있는데 특정 필드가 업데이트되면 특정 recordID에 대해 사용자에게 알려야합니다. 브라우저의 단일 인스턴스를 열었을 때 모든 것이 잘 작동하지만 동일한 컴퓨터 나 다른 컴퓨터에서 다른 탭이나 브라우저를 열면 sqldepdencychange 이벤트가 여러 번 발생합니다. 다음은 각 브라우저 인스턴스에 대해 여러 번 발생하는 sqldepdency 신호음기

내 허브 코드

다음
public class MessagesHub : Hub 
    { 
     private static string conString = ConfigurationManager.ConnectionStrings["FleetLink_DB"].ToString(); 

     private static string hostName = ""; 


     public static void SendMessages(string hName) 
     { 
      IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>(); 
      hostName = hName; 
      context.Clients.Group(hostName).updateMessages(hName); 
     } 

     public Task leaveGroup(string hName) 
     { 
      return Groups.Remove(Context.ConnectionId, hName); 
     } 

     public Task joinGroup(string hName) 
     { 
      return Groups.Add(Context.ConnectionId, hName); 
     } 
} 

내 signalr 스크립트 파일입니다 아래

$(function() { 
      var dialog, form 
      // Declare a proxy to reference the hub. 

      var notifications = $.connection.messagesHub; 
      //debugger; 
      //Create a function that the hub can call to broadcast messages. 
      notifications.client.updateMessages = function (hName) { 
       alert("testing"); 
       getoneMessages(hName) 
      }; 

      $.connection.hub.logging = true; 
      $.connection.hub.start().done(function() { 
       var hostName = getUrlVars()["System_Name"]; 
       notifications.server.joinGroup(hostName); 
      }).fail(function (e) { 
       alert(e); 
      }); 
     }); 

     function getUrlVars() { 
      var vars = [], hash; 
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 
      for (var i = 0; i < hashes.length; i++) { 
       hash = hashes[i].split('='); 
       vars.push(hash[0]); 
       vars[hash[0]] = hash[1]; 
      } 
      return vars; 
     } 

     function getoneMessages(hName) { 
      var tbl = $('#selectable'); 
      //alert('mesgID=' + mesgID) 
      //var tbl = $('#selectable'); 
      $.ajax({ 
       url: '/controller/view', 
       cache: false, 
       contentType: 'application/html ; charset:utf-8', 
       type: 'GET', 
       dataType: 'html' 
      }).success(function (result) { 
       //alert(result); 
       tbl.empty().append(result); 
      }).error(function (exception) { 
       //alert('failed= ' + exception); 
      }); 
     } 

     window.onbeforeunload = function (e) { 
      var hostName = getUrlVars()["System_Name"]; 
      notifications.server.joinGroup(hostName); 
      $.connection.hub.stop(); 

     }; 

내 partialview 코드는 RegisterForNotification에 대한 정의와 depdendency_onchange 이벤트와 함께입니다

public PartialViewResult SignalRTesterPartialView() 
{ 
/...COde not included for brevity..../ 
    RegisterForNotifications(ID); 
} 



public void RegisterForNotifications(int mID) 
     { 
      var efConnectionString = ConfigurationManager.ConnectionStrings["DB"].ConnectionString; 
      var builder = new EntityConnectionStringBuilder(efConnectionString); 
      var regularConnectionString = builder.ProviderConnectionString; 

      string commandText = null; 


      commandText = "select ID,Status,Name from tblABC where ID=" + strID; 

       using (SqlConnection connection = new SqlConnection(regularConnectionString)) 
       { 
        using (SqlCommand command = new SqlCommand(commandText, connection)) 
        { 
         connection.Open(); 

         var dependency = new SqlDependency(command); 
         dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); 

         // NOTE: You have to execute the command, or the notification will never fire. 
         var reader = command.ExecuteReader(); 
        } 
       } 

     } 

     private void dependency_OnChange(object sender, SqlNotificationEventArgs e) 
     { 
      if (e.Type == SqlNotificationType.Change && e.Info== SqlNotificationInfo.Update) 
      { 
       MessagesHub.SendMessages(hName); 
      } 

      RegisterForNotifications(1012); 


     } 

왜 각 addit과 함께 sendmessages를 여러 번 실행하는지 확실하지 않습니다. ional 브라우저 인스턴스를 엽니 다. 어떤 포인터가 도움이 될 것입니다!

답변

1

제거 EventHandler 당신은

private void dependency_OnChange(object sender, SqlNotificationEventArgs e) 
{ 
    if (e.Type == SqlNotificationType.Change && e.Info== SqlNotificationInfo.Update) 
    { 
     MessagesHub.SendMessages(hName); 
    } 

    //remove event handler 
    SqlDependency dependency = sender as SqlDependency; 
    dependency.OnChange -= new OnChangeEventHandler(dependency_OnChange); 

    RegisterForNotifications(1012); 
} 
함께 할 때