c# - Using Dispatcher to change a label's foreground throws an exception -


i trying make cpu friendly infinite loop update label every 2 seconds.

when comes update label, can use dispatcher change content , tooltip values, can't change foreground reason.

invalidoperationexception: can not use dependencyobject belongs thread freezable parent.

there code:

private void setping(brush foreground, string content, string tooltip) {     try     {         this.dispatcher.begininvoke(dispatcherpriority.send, (action)(() =>         {             this.ping.content = content;             this.ping.tooltip = tooltip;         }));          // this.dispatcher or this.ping.dispatcher throws same error         this.ping.dispatcher.begininvoke(dispatcherpriority.normal, (action)(() =>         {             this.ping.foreground = foreground;         }));     }     catch (exception)     {     } } 

and i'm calling code performping method here:

new thread(() => {     while (true)     {         this.performping(this.host);         thread.sleep(1);     } }).start(); 

(yes, know not cpu-friendly loop, made testing purposes).

thanks peter duniho's answer, figured out brush object created in background thread, , thing caused issue. creating brush in dispatcher call solves issue.

private void setping(long ping, string content, string tooltip) {     try     {         this.dispatcher.begininvoke(dispatcherpriority.send, (action)(() =>         {             this.ping.content = content;             this.ping.tooltip = tooltip;             this.setdock();         }));          if (this.enablecolors)         {             this.ping.dispatcher.begininvoke(dispatcherpriority.send, (action)(() =>             {                 this.ping.foreground = this.getcolorbyping(ping);             }));         }     }     catch (exception ex)     {     } } 

where getcolorbyping() returns return (solidcolorbrush)new brushconverter().convertfromstring("#b71c1c");


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -