WPF C# - Editing a listbox from another thread -


i realize i'm doing pretty silly, i'm in middle of learning wpf , know how this.

i have window listbox on it. listbox being used deliver status messages program while it's running. example "server started" "new connection @ ip #" etc. wanted updating in background, spawned new thread handling updating this, when made call add item error message "the calling thread cannot access object because different thread owns it."

any idea how can update listbox thread? or in background, etc.


update

if using c# 5 , .net 4.5 or above can avoid getting on thread in first place using async , await, e.g.:

private async task<string> simlongrunningprocessasync() {     await task.delay(2000);     return "success"; }  private void button_click(object sender, routedeventargs e) {     button.content = "running...";     var result = await simlongrunningprocessasync();     button.content = result; } 

easy:

dispatcher.begininvoke(new action(delegate()    {      mylistbox.items.add("new item"));   })); 

if in code-behind. otherwise can access dispatcher (which on every uielement) using:

application.current.mainwindow.dispatcher.begininvoke(... 

ok thats lot in 1 line let me go on it:

when want update ui control you, message says, have ui thread. there built in way pass delegate (a method) ui thread: dispatcher. once have dispatcher can either invoke() of begininvoke() passing delegate run on ui thread. difference invoke() return once delegate has been run (i.e. in case listbox's new item has been added) whereas begininvoke() return other thread calling can continue (the dispatcher run delegate can straight away anyway).

i passed anonymous delegate above:

delegate() {mylistbox.items.add("new item");} 

the bit between {} method block. called anonymous because 1 created , doesnt have name (usually can using lambda expression in case c# cannot resolve begininvoke() method call). or have instantiated delegate:

action mydelegate = new action(updatelistmethod);  void updatelistmethod()  {   mylistbox.items.add("new item"); } 

then passed that:

dispatcher.invoke(mydelegate); 

i used action class built in delegate have created own - can read more delegates on msdn going bit off topic..


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -