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();
}