c# - Cancel a static async function with a timeout -
i need cancel updatedatabase() function if takes more 2 minutes. 've tried cancellationtokens , timers couldn't manage solve (couldn't find appropriate example).
could please me on this?
app.xaml.cs
protected override async void onlaunched(launchactivatedeventargs args) {    await performdatafetch(); }  internal async task performdatafetch() {    await localstorage.updatedatabase(); } localstorage.cs
public async static task<bool> updatedatabase() {   await ..// download files   await ..// check files   await ..// run controles } edited classes according answers.
app.xaml.cs stays same. updatedatabase() edited , new method runupdate() added in localstorage.cs:
public static async task updatedatabase() {     cancellationtokensource source = new cancellationtokensource();     source.cancelafter(timespan.fromseconds(30)); // how time has update process     task<int> task = task.run(() => runupdate(source.token), source.token);      await task; }  private static async task<int> runupdate(cancellationtoken cancellationtoken) {     cancellationtoken.throwifcancellationrequested();     await ..// download files     cancellationtoken.throwifcancellationrequested();     await ..// check files     cancellationtoken.throwifcancellationrequested();     await ..// run controles } i know not way , better point start newbies me.
you need pass cancellationtoken updatedatabase function , check token after each await calling throwifcancellationrequested. see this
Comments
Post a Comment