在我的Windows应用商店应用中,我有一个方法
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()));
}
我用来下载和初始化(下载,解析|项目中的广告。等待此方法
...
await AdReader.InitAds()
...
问题是广告服务器有时响应速度非常慢。我希望有一个超时,比如这个方法运行10秒。如果它没有在此超时时间内完成,我希望它被杀死并且我的代码将继续。
实现此目的的最佳方法是什么?我发现How to cancel a Task in await?但是它使用了一个TaskFactory,当我尝试这种方法并在Task.Run中调用我的方法时,它不再等待,代码仍在继续。
修改
StartRotation也是一个异步方法,调用另一个异步方法
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();
}
答案 0 :(得分:3)
取消是合作的。您只需将CancellationToken
传递到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)));
}
然后这样称呼它:
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await InitAds(cts.Token);