c# - Background worker does not work properly in do work event in wpf -
i have read post did not me :
background worker not work in wpf
i using background worker in wpf(c#) , want when reading text file , shows "loading ...." not show. code :
private delegate void upmdlg(); private delegate void upmdlg2(); private void callmetoread() { streamreader str = new streamreader("c:\\test.txt"); while (!str.endofstream) { richtextbox1.appendtext(str.readtoend()); } } private void callmetochangelabel() { label1.foreground = brushes.red; label1.content = "loading ...."; } private void window_loaded(object sender, routedeventargs e) { label1.foreground = brushes.yellow; label1.content = "idle"; backgroundworker bg = new backgroundworker(); bg.dowork += delegate(object s, doworkeventargs args) { upmdlg mo = new upmdlg(callmetochangelabel); label1.dispatcher.begininvoke(mo, dispatcherpriority.normal); upmdlg mo2 = new upmdlg(callmetoread); richtextbox1.dispatcher.begininvoke(mo2, dispatcherpriority.normal); }; bg.runworkercompleted += delegate(object s, runworkercompletedeventargs arg) { label1.foreground = brushes.green; label1.content = "done ...."; }; bg.runworkerasync(); }
thanks help.
try synchronizationcontext.current
post execution ui code. works me well:
private void window_loaded(object sender, routedeventargs e) { label1.foreground = brushes.yellow; label1.content = "idle"; var context = synchronizationcontext.current; backgroundworker bg = new backgroundworker(); bg.dowork += (o, args) => { context.post(state => callmetochangelabel(),null); context.post(state => callmetoread(), null); }; bg.runworkercompleted += (o, args) => { label1.foreground = brushes.green; label1.content = "done ...."; }; bg.runworkerasync(); }
btw: posts describes how synchronizationcontext works: it's synchronizationcontext , understanding synchronizationcontext
Comments
Post a Comment