I need to cancel the UpdateDatabase() function if it takes more than 2 minutes. I 've tried cancellationtokens and timers but I couldn't manage to solve this (couldn't find any appropriate example).

Could you please help 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 my classes according to answers.

App.xaml.cs stays as same. UpdateDatabase() is edited and the new method RunUpdate() added in LocalStorage.cs:

public static async Task UpdateDatabase()
{
    CancellationTokenSource source = new CancellationTokenSource();
    source.CancelAfter(TimeSpan.FromSeconds(30)); // how much time has the 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 this is not the only way and could be better but a good point to start for newbies like me.

有帮助吗?

解决方案

You need to pass a CancellationToken to the UpdateDatabase function and check the token after each await by calling ThrowIfCancellationRequested. See this

其他提示

You could try this:

const int millisecondsTimeout = 2500;
Task updateDatabase = LocalStorage.UpdateDatabase();
if (await Task.WhenAny(updateDatabase, Task.Delay(millisecondsTimeout)) == updateDatabase)
{
    //code
}
else
{
    //code
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top