How to change the contents of shortcuts using timers throwing an InvalidOperationException

I am creating an application and I am using the timer in this application to change the contents of shortcuts in WPF C # .NET.

In the expired timer event, I write the following code

lblTimer.Content = "hello"; 

but it throws an InvalidOperationException and throws a message. The calling thread cannot access this object because another thread belongs to it.

I am using the .NET framework 3.5 and WPF with C #.

Please help me.
Thanks in advance.

+4
source share
3 answers

lblTimer been declared in your main GUI thread and you are trying to update it from another thread -> you get this error.

This link "Accessing WPF controls in a stream without a user interface" contains a description of your problem and a fix for it.

+3
source

For .NET 4.0, it is much easier to use DispatcherTimer. The event handler is then located in the user interface thread, and it can directly set the properties of the control.

 private DispatcherTimer updateTimer; private void initTimer { updateTimer = new DispatcherTimer(DispatcherPriority.SystemIdle); updateTimer.Tick += new EventHandler(OnUpdateTimerTick); updateTimer.Interval = TimeSpan.FromMilliseconds(1000); updateTimer.Start(); } private void OnUpdateTimerTick(object sender, EventArgs e) { lblTimer.Content = "hello"; } 
+11
source

InvokeRequired does not work in wpf.

The correct way to update a GUI element belonging to another thread is as follows:

Declare this at the module level:

 delegate void updateLabelCallback(string tekst); 

This is the method of updating your label:

 private void UpdateLabel(string tekst) { if (label.Dispatcher.CheckAccess() == false) { updateLabelCallback uCallBack = new updateLabelCallback(UpdateLabel); this.Dispatcher.Invoke(uCallBack, tekst); } else { //update your label here } } 
+1
source

Source: https://habr.com/ru/post/1307989/


All Articles