简体   繁体   中英

How to cancel async Task after a period of time

In my Windows Store app I have a method

public async static Task InitAds()
{
    Debug.WriteLine("API: Loading Ad images");
    await Task.WhenAll(ads.Select(l => l.Value).Where(l=>l!=null).Select(l => l.StartRotation()));
 }

I use to download and initialize (download, parse| Ads in a project. This method is awaited when called

...
await AdReader.InitAds()
...

The problem is that Ads server sometimes responds very slowly. I want to have a timeout, say 10 seconds for this method to run. If it does not finish in this timeout, I want it to be killed and my code to continue.

What is the best way to implement this? I found How to cancel a Task in await? but it uses a TaskFactory and when I try that approach and call my method in Task.Run it is not awaited and the code continues.

Edit:

The StartRotation is also an async method calling another async methods

public async Task StartRotation(CancellationToken ct)
{
        if (Images.Count == 1)
        {
            await Image.LoadAndSaveImage(ct);
        }

        if (Images.Count <2) return;

        foreach (var img in Images)
        {
            await img.LoadAndSaveImage(ct);
        }

        Delay = Image.Delay;
        DispatcherTimer dt = new DispatcherTimer();
        dt.Interval = TimeSpan.FromMilliseconds(Delay);
        dt.Tick += (s, e) =>
        {
            ++index;
            if (index > Images.Count - 1)
            {
                index = 0;
            }
            Image = Images[index];
        };
        dt.Start();
    }

Cancellation is cooperative. You just need to pass CancellationToken into your StartRotation :

public async static Task InitAds(CancellationToken token)
{
  Debug.WriteLine("API: Loading Ad images");
  await Task.WhenAll(ads.Select(l => l.Value).Where(l=>l!=null).Select(l => l.StartRotation(token)));
}

And then call it as such:

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await InitAds(cts.Token);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM