DispatcherTimer runs on your user interface thread, so when it launches your check, your user interface will probably freeze when the DispatcherTimer_Tick message is executed. If it takes 2 seconds for DispatcherTimer_Tick and every 3 seconds you freeze the user interface for 2 seconds. Users will not like it.
All service calls should be made in a thread other than the UI so that you do not block the user interface, so I suggest using a timer and doing something like this:
public MainViewModel() { _stTimer = new System.Threading.Timer(Timer_Tick,null,3000,3000); _dispatcher = Dispatcher.CurrentDispatcher; } private void Timer_Tick(object sender) { Account.Ping = _service.Ping(Account); //Refresh data in dictionary _freshUsers = _service.LoadUsers(Account); _users.Clear(); SelectedUsersIndex = 1; foreach (var freshUser in _freshUsers) { _users.Add(freshUser); } for(int i=0;i<Account.Ping.Rp; i++) { //check if you have new messanges if (Account.Ping.Rp > 0) { Rp message = _service.LoadRp(Account); _messages.Add(message); } } _dispatcher.BeginInvoke((Action)(()=>{OnPropertyChanged("Messages");})); }
Here we use the system timer to check for changes in another thread, so your user interface will not be affected by any processing. When we want to notify the user interface that a change has occurred, we can use _dispatcher (the user interface manager that we create in the constructor) for the "BeginInvoke" method in the user interface thread.
This will make your application faster. A good rule of thumb is to disable the Dispatcher thread as much as possible; use it only when you are doing something with the user interface. All other processing should be in the background thread.
Hope this helps
source share