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;
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);
Clients.Client(ConnectionId).NotificationToClient(NotificationResult);
await Task.Delay(1000);
});
}
}
}
What I have tried:
public override Task OnDisconnected(bool stopCalled)
{
timer.Stop();
timer.Enabled = false;
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;
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);
Clients.Client(ConnectionId).NotificationToClient(NotificationResult);
await Task.Delay(6000);
}
});
}
}
}