C# WPF Indeterminate progress bar -
please suggest why following doesn't work? want display indeterminate progressbar starts when button clicked, after i've done work set indeterminate progressbar false stop it.
however when run code below indeterminate progressbar doesnt start. tried commenting out line this.progressbar.isindeterminate = false;
, , when progressbar start doesn't terminate.
private void generatecsv_click(object sender, routedeventargs e) { this.dispatcher.invoke(dispatcherpriority.normal, new action(delegate () { this.progressbar.isindeterminate = true; //do work thread.sleep(10 * 1000); this.progressbar.isindeterminate = false; })); }
your code can't work because "do work" happening on same thread
on ui works. so, if thread
busy "work", how can handle ui animation progressbar
@ same time? have put "work" on thread
, ui thread
free , can job progressbar
(or other ui controls).
1) create method work , returns task
, can "awaited" completion:
private async task doworkasync() { await task.run(() => { //do work here thread.sleep(2000); }); }
2) put async
modifier on generatecsv_click
:
private async void generatecsv_click(object sender, routedeventargs e)
3) throw away "dispatcher" / "invoke" etc stuffs, , use doworkasync
way:
private async void button_click(object sender, routedeventargs e) { pb.isindeterminate = true; await doworkasync(); pb.isindeterminate = false; }
so, what's happening now? when generatecsv_click
encounters first await
... begins work automatically on thread
, leaving ui thread
free operate , animate progressbar
. when work finished, control of method returns ui thread
sets isindeterminate
false.
here can find msdn tutorial on async
programming: https://msdn.microsoft.com/en-us/library/mt674882.aspx if google "c# async await", you'll find dozens of tutorials, examples , explanations ;)
Comments
Post a Comment