c# - Asynchronous Thread Lifetime & WPF UI Update -
on button click have fired call startcontinuousthread
keeps polling server every 1 second.
public class threadswindow { cancellationtokensource wtoken = new cancellationtokensource(); private void btnstarttest_click(object sender, routedeventargs e) { startcontinuousthread(); } void startcontinuousthread() { while(true) { var fact = task.factory.startnew(() => { callserver(); task.delay(1000, wtoken.token); }, wtoken.token); } } }
startcontinuousthread
starts executing, btnstarttest_click event handler
finishes execution.
how
startcontinuousthread method
able update ui in case?i wonder whether
startcontinuousthread
terminated event handler, since there no wait keyword re-joining.
please help!
if goal poll server every second have number of problem.
there no loop. execute method once , stop.
you create task using
delay
, ignore it. ought creating continuation of task rest of work not second.
here implementation addresses issues:
private async task startcontinuousthread(cancellationtoken token) { while (true) { token.throwifcancellationrequested(); await task.run(() => callserver()); await task.delay(1000, token); } }
another possibility, if you're using older version of c#, use timer run code every second.
as updating ui; can freely anywhere outside of call task.run
in example. in example you'd need use mechanism marshal ui thread, such capturing ui's synchronization context , posting it.
Comments
Post a Comment