.net - How to update gui in c# wpf from asynchronous method callback -
i've search on stackoverflow , in net , couldn't find solution problem.
i read stream in async way. want callback update gui
[stathread] private void clientloggedcallback(iasyncresult res) { try { mailclient.helpers.client.getinstance().client.getstream().endwrite(res); mailclient.helpers.client.getinstance().asyncrecieveencryptedprotocolmessage(new asynccallback(logininfo_recieved)); } catch { } } [stathread] private void logininfo_recieved(iasyncresult res) { try { mailclient.helpers.client.getinstance().client.getstream().endread(res); mailclient.asyncstate state = (mailclient.asyncstate)res.asyncstate; string answer = aes.decryptstringfrombytes_aes(state.buffer, state.aes_key, state.aes_iv); if (answer.contains("ok")) { string[] answer_params = answer.split(','); loggeduserinfo.user_id = convert.toint32(answer_params[1]); loggeduserinfo.user_login = answer_params[2]; //zalogowano //this.targetwindow = new messagelistswindow(); dispatcher.currentdispatcher.invoke(dispatcherpriority.background, new action(() => this.targetwindow = new messagelistswindow())); //system.windows.application.current.dispatcher.invoke(dispatcherpriority.background, new action(() => this.targetwindow = new messagelistswindow())); } else { //zle dane system.windows.messagebox.show("zle dane"); } } catch(exception exep) { } }
this declaration of asyncsendencryptedprotocolmessage
asyncsendencryptedprotocolmessage(string message, asynccallback callback)
use function
clientstream.beginwrite(encryptedmessage, 0, encryptedmessage.length, callback, st);
when code executes exception "the calling thread must sta, because many ui components require this." read "setapartmentstate(apartmentstate.sta);" don't know how apply callback. i've tried stathread attribute doesn't work. use mvvm light framework.
stacktrace
" w system.windows.threading.dispatcherobject.verifyaccess()\r\n w system.windows.application.get_mainwindow()\r\n w mailclient.viewmodel.mainwindowmodel.logininfo_recieved(iasyncresult res) w c:\\users\\oem\\documents\\visual studio 2012\\projects\\mvvmlight3\\mailclient\\viewmodel\\mainwindowmodel.cs:wiersz 171"
public static void dispatch(this dispatcherobject source, action func) { if (source.dispatcher.checkaccess()) func(); else source.dispatcher.invoke(func); }
and use this:
mailclient.helpers.client.getinstance() .asyncrecieveencryptedprotocolmessage(new asynccallback(()=> application.current.mainwindow.dispatch(logininfo_recieved)));
Comments
Post a Comment