title: Cancel a static async function with a timeout
body: <p>I need to cancel the UpdateDatabase() function if it takes more than 2 minutes. I 've tried <em>cancellationtokens</em> and <em>timers</em> but I couldn't manage to solve this (couldn't find any appropriate example).</p>
  
  <p>Could you please help me on this?</p>
  
  <p><strong>App.xaml.cs</strong></p>
  
  <pre><code>protected override async void OnLaunched(LaunchActivatedEventArgs args)
  {
     await PerformDataFetch();
  }
  
  internal async Task PerformDataFetch()
  {
     await LocalStorage.UpdateDatabase();
  }
  </code></pre>
  
  <p><strong>LocalStorage.cs</strong></p>
  
  <pre><code>public async static Task&lt;bool&gt; UpdateDatabase()
  {
    await ..// DOWNLOAD FILES
    await ..// CHECK FILES
    await ..// RUN CONTROLES
  }
  </code></pre>
  
  <p><em><strong>Edited my classes according to answers.</em></strong> </p>
  
  <p><em>App.xaml.cs</em> stays as same. <em>UpdateDatabase()</em> is edited and the new method <em>RunUpdate()</em> added in <em>LocalStorage.cs</em>:</p>
  
  <pre><code>public static async Task UpdateDatabase()
  {
      CancellationTokenSource source = new CancellationTokenSource();
      source.CancelAfter(TimeSpan.FromSeconds(30)); // how much time has the update process
      Task&lt;int&gt; task = Task.Run(() =&gt; RunUpdate(source.Token), source.Token);
  
      await task;
  }
  
  private static async Task&lt;int&gt; RunUpdate(CancellationToken cancellationToken)
  {
      cancellationToken.ThrowIfCancellationRequested();
      await ..// DOWNLOAD FILES
      cancellationToken.ThrowIfCancellationRequested();
      await ..// CHECK FILES
      cancellationToken.ThrowIfCancellationRequested();
      await ..// RUN CONTROLES
  }
  </code></pre>
  
  <p>I know this is not the only way and could be better but a good point to start for newbies like me. </p>