multithreading - C# Execute method after background thread finished -
i'm using thread run calculation in background of program. start thread @ start of program. if press button before thread finished open statusbar , "openedstatus" set true.
this show threads current progress , after thread has finished execute last part of code:
if (openedstatus) { sb.close(); validatebeforesave(); }
this part of code throw exception though because can't close statusbar cross-thread.
now question is: how can execute last part of code after thread finished?
private statusbar sb = new statusbar(); private void startvoorraadcalculationthread() { sb.setmaxprogress(data.getproducten().getproductencopy().count); thread thread = new thread(new threadstart(this.run)); thread.start(); while (!thread.isalive) ; } private void run() { (int = 0; < data.getproducten().getproductencopy().count; i++ ) { sb.setprogress(i); sb.setstatus("calculating voorraad: " + (i+1) + "/" + data.getproducten().getproductencopy().count); data.getproducten().getproductencopy()[i].gettotaalvoorraad(data.getmaten()); } if (openedstatus) { sb.close(); validatebeforesave(); } calculationfinished = true; }
using backgroundworker fixed problem:
private void startvoorraadcalculationthread() { sb.setmaxprogress(data.getproducten().getproductencopy().count); backgroundworker bw = new backgroundworker(); bw.dowork += new doworkeventhandler(bw_dowork); bw.runworkercompleted += new runworkercompletedeventhandler(bw_runworkercompleted); bw.runworkerasync(); } private void bw_dowork(object sender, doworkeventargs e) { (int = 0; < data.getproducten().getproductencopy().count; i++) { sb.setprogress(i); sb.setstatus("calculating voorraad: " + (i + 1) + "/" + data.getproducten().getproductencopy().count); data.getproducten().getproductencopy()[i].gettotaalvoorraad(data.getmaten()); } } private void bw_runworkercompleted(object sender, runworkercompletedeventargs e) { if (openedstatus) { sb.close(); validatebeforesave(); } calculationfinished = true; }
Comments
Post a Comment