c# - How to prevent GUI from locking up during operation? -


here code:

private void runcoinflip() {     togglecontrolsusability();      task task = new task(coinflippinganimation);     task.start();     task.wait();      togglecontrolsusability();      flipoutcome = piccoin.image == coinsideimages[0] ? coinsides.heads : coinsides.tails;     lblresult.text = userguess == flipoutcome ? "congrats won!" : "too bad lost."; }  private void togglecontrolsusability() {     btnheads.enabled = !btnheads.enabled;     btntails.enabled = !btntails.enabled; }  private void coinflippinganimation() {     random rng = new random();      (int = 0; < 15; i++)     {         int side = rng.next(0, coinsideimages.length);         piccoin.image = coinsideimages[side];          thread.sleep(100);     } } 

basically, buttons should frozen during operation , unfrozen afterwards, , coin flipping animation flips coin. unfortunately, gui locked during animation can't move window or resize.

i've been reading async , await i'm not sure if applies here or how add it. different results try lead either blocking, instant unfreezing of controls, or cross-thread execution errors.

there's no need thread here, since time being spent in thread.sleep , not random number generation. so, simple async solution be:

private async task runcoinflipasync() {   togglecontrolsusability();    await coinflippinganimationasync();    togglecontrolsusability();    flipoutcome = piccoin.image == coinsideimages[0] ? coinsides.heads : coinsides.tails;   lblresult.text = userguess == flipoutcome ? "congrats won!" : "too bad lost."; }  private async task coinflippinganimationasync() {   random rng = new random();    (int = 0; < 15; i++)   {     int side = rng.next(0, coinsideimages.length);     piccoin.image = coinsideimages[side];      await task.delay(100);   } } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -