c# - wpf background thread updating UI control -
i have working app adds new new ribbontab , new child control grid.
i put action onto background thread child control can take while gather data database, etc.
i have following code far:
ribbon ribbon_main = new ribbon(); grid grid_main = new grid(); thread newthread2 = new thread(new threadstart(delegate { graphing_template.add_report(); })); newthread2.setapartmentstate(apartmentstate.sta); //is required? newthread2.start(); class graphing_template() { static void add_report() { ribbontab rt1 = new ribbontab(); mainwindow.ribbon_main.items.add(rt1); // create control information database, etc. // add control mainwindow.grid_main } }
i new report control created in background , added main ui when ready.
the solution went is:
backgroundworker worker = new backgroundworker(); worker.dowork += delegate(object s, doworkeventargs args) { datatable dt1 = new datatable(); ---- fill datatable args.result = datagrid_adventureworks_dt(); }; worker.runworkercompleted += delegate(object s, runworkercompletedeventargs args) { datatable dt1 = (datatable)args.result; datagrid_main.itemssource = dt1.asdataview(); };
private void window_loaded(object sender, routedeventargs e) { test4(); } private void test1() { while (true) { this.title = datetime.now.tostring(); system.threading.thread.sleep(5000); //locks app } } private void test2() { var thd = new system.threading.thread(() => { while (true) { this.title = datetime.now.tostring(); //exception system.threading.thread.sleep(5000); } }); thd.start(); } private void test3() { //do work on background thread var thd = new system.threading.thread(() => { while (true) { //use dispatcher manipulate ui this.dispatcher.begininvoke((action)(() => { this.title = datetime.now.tostring(); })); system.threading.thread.sleep(5000); //there's nothing ever stop thread! } }); thd.start(); } private async void test4() { //if using .net 4.5 can use async keyword //i _think_ computation in async method runs on ui thread, //so don't use ray tracing, //but db or network access workstation can on //other (ui) work whilst it's waiting while (true) { await task.run(() => { system.threading.thread.sleep(5000); }); this.title = datetime.now.tostring(); } }
Comments
Post a Comment