Reputation: 182
I have a UserControl
. On Load event of this UserControl
, i am creating a timer
with an interval of 1 sec. In Timer_tick
function i'm getting the current Date
and then Iterating through a LIST
that contains some other UserControls
. And checking if the Current Date matches the Date stored in List then perform something. It works fine till here. But as soon as i get Current time
and compare it with the time stored in LIST. it behaves weird. No 1 it never matches the time on Windows taskbar showing.(okey still fine). but when a condition fulfills, Time stored in LIST and Current time matches. It perform some function but then it just keeps performing it and even the current time is changed and condition is false still it keeps doing. What i am doing wrong ?
Timer timer = new Timer();
private async void TodoListControl_OnLoaded(object sender, RoutedEventArgs e) // UserControl Load
{
timer.Interval = (1000);
timer.Tick += Timer_Tick;
timer.Start();
}
Timer_tick
private void Timer_Tick(object sender, EventArgs e)
{
string date = now.ToShortDateString();
foreach (var item in result)
{
if(item.Date.Trim() == date.Trim() && item.Time.Trim() == now.ToString("t").Trim())
{
ParentWindow.SnackbarNotification.IsActive = false;
ParentWindow.SnackbarNotification.Message.Content = $"{item.Title} - {item.Date} - {item.Time}";
ParentWindow.SnackbarNotification.IsActive = true;
}
else
{
ParentWindow.SnackbarNotification.IsActive = false;
}
}
}
Upvotes: 0
Views: 1279
Reputation: 182
Finally found the reason. If current time fetched using now.ToString("t")
is 12:30 PM and it matches stored time 12:30 PM then the condition is true and notification is shown but then the condition if(item.Date.Trim() == date.Trim() && item.Time.Trim() == now.ToString("t").Trim())
never becomes false. Because time that i get every second using this now.ToString("t")
never updates.
i mean when first time i fetched now.ToString("t")
in condition check it always remains the same as 12:30
. it never increases. And the reason of this was now
was defined globally as DateTime now = DateTime.Now;
so idk why but every time in a local scope i run now.ToString("t")
i get same time that it gets on first run.
So i declared now locally in my function and every second this DateTime now = DateTime.Now;
also runs before now.ToString("t")
and i get the latest time
Upvotes: 1