7

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.

Korki Korkig
  • 2,736
  • 9
  • 34
  • 51
  • you can use WaitOne if you can wait till the call finishes with a timeout or you need to implement your own timer.. Refer http://stackoverflow.com/questions/5973342/how-to-handle-timeout-in-async-socket – now he who must not be named. Jul 31 '13 at 11:22

2 Answers2

5

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

Community
  • 1
  • 1
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
1

You could try this:

const int millisecondsTimeout = 2500;
Task updateDatabase = LocalStorage.UpdateDatabase();
if (await Task.WhenAny(updateDatabase, Task.Delay(millisecondsTimeout)) == updateDatabase)
{
    //code
}
else
{
    //code
}
rechandler
  • 756
  • 8
  • 22