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.