Click here to Skip to main content
15,881,791 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have started a timer when my hub connection is established in PushNotificationData method by clients requests.

As per timer interval, it does fetch the records from the db and push to the clients. but when clients got disconnected ,this timer has to be stopped instead of pulling continuously.

So I have used OnDisconnected event to stop the timer. but unfortunately timer not getting stopped

public class NotifyHub : Hub
    {
        private string ConnectionId;
        private int UserId;
        private int UserTypeId;

        Timer timer = new Timer();

        public override Task OnConnected()
        {
            ConnectionId = Context.ConnectionId;
            return base.OnConnected();
        }
        public override Task OnDisconnected(bool stopCalled)
        {
            timer.Stop();
            timer.Enabled = false;
            //logic code removed for brevity
            return base.OnDisconnected(stopCalled);
        }
        public void PushNotificationData(Int32 userId, Int16 userTypeId)
        {

            UserId = userId;
            UserTypeId = userTypeId;
            ConnectionId = Context.ConnectionId;

            timer.Elapsed += Timer_Elapsed1;
            timer.Interval = 6000;
            timer.Enabled = true;
            timer.Start();

        }
    private void Timer_Elapsed1(object sender, ElapsedEventArgs e)
        {
            var notificationParams = new PushNotificationRequest
            {
                FilterProperty = new Common.Filters.FilterProperty { Offset = 0, RecordLimit = 0, OrderBy = "datechecked desc" },
                Filters = new List<Common.Filters.FilterObject> { new Common.Filters.FilterObject { LogicOperator = 0, ConditionOperator = 0, Function = 0, FieldName = "", FieldValue = "", FieldType = 0 } }
            };
            using (INotificationManager iNotifity = new NotificationManager())
            {
                var taskTimer = Task.Run(async () =>
                {                        
                        var NotificationResult = iNotifity.GetPushNotificationData(notificationParams, UserId, UserTypeId);
                        //Sending the response data to all the clients based on ConnectionId through the client method NotificationToClient()
                        Clients.Client(ConnectionId).NotificationToClient(NotificationResult);
                        //Delaying by 6 seconds.
                        await Task.Delay(1000);
                        //}
                  });
            }
        }  
    }


What I have tried:

public override Task OnDisconnected(bool stopCalled)
       {
           timer.Stop();
           timer.Enabled = false;
           //logic code removed for brevity
           return base.OnDisconnected(stopCalled);
       }


When I debug it, it shows timer enabled=true even after OnDisconnected fires.


Update: Instead of timer I have written like below. due to this loop I got an performance issue on server.

public void PushNotificationData(Int32 userId, Int16 userTypeId)
        {
            UserId = userId;
            UserTypeId = userTypeId;
            ConnectionId = Context.ConnectionId;
            //timer = new Timer();
            //timer.Elapsed += Timer_Elapsed1;
            //timer.Interval = 6000;
            //timer.Enabled = true;
            //timer.Start();

            lock (this)
            {
                var notificationParams = new PushNotificationRequest
                {
                    FilterProperty = new Common.Filters.FilterProperty { Offset = 0, RecordLimit = 0, OrderBy = "datechecked desc" },
                    Filters = new List<Common.Filters.FilterObject> { new Common.Filters.FilterObject { LogicOperator = 0, ConditionOperator = 0, Function = 0, FieldName = "", FieldValue = "", FieldType = 0 } }
                };
                using (INotificationManager iNotifity = new NotificationManager())
                {
                    var taskTimer = Task.Run(async () =>
                    {
                        while (true)
                        {
                            var NotificationResult = iNotifity.GetPushNotificationData(notificationParams, UserId, UserTypeId);
                            //Sending the response data to all the clients based on ConnectionId through the client method NotificationToClient()
                            Clients.Client(ConnectionId).NotificationToClient(NotificationResult);
                            //Delaying by 6 seconds.
                            await Task.Delay(6000);
                        }
                    });
                }
            }
        }
Posted
Updated 4-Jan-17 0:13am
v2
Comments
Andy Lanng 4-Jan-17 4:17am    
err... you... but... aaahhhg - so many things wrong!

The hub is, or at least should be a singleton. You can't create a timer per connection this way.

Without knowing more about your system, I suggest you keep the timer running and broadcast what you need constantly. Don't turn off the timer for everyone just because one person has disconnected.

This also means that you should start the timer in the constructor rather that when someone connects. That way pain lies
King Fisher 4-Jan-17 6:04am    
How to create timer per connection ?
Andy Lanng 4-Jan-17 6:07am    
Your timer interval is 6 seconds. There's no point creating 1 per connection because they'd be firing constantly. Just have 1 timer that broadcasts to everyone who happens to be connected.
King Fisher 4-Jan-17 6:15am    
pls Check the updates on "What I have tried:" section

Due that loop I got an performance issue on the server, So suddenly we reverted the codes back. And the thing which you are suggesting is also similar right ?
Andy Lanng 4-Jan-17 6:21am    
yeah, pretty much. I wouldn't do it that way but I see no problem with it :~)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900