我正在阅读TAP Whitepaper,并且对第 22 页上为实现超时而给出的示例感到困惑:
“考虑一个 UI 应用程序,它想要下载图像并在下载图像时禁用 UI。但是,如果下载时间过长,则应重新启用 UI 并放弃下载。”
public async void btnDownload_Click(object sender, EventArgs e)
{
btnDownload.Enabled = false;
try
{
Task<Bitmap> download = GetBitmapAsync(url);
if (download == await Task.WhenAny(download, Task.Delay(3000)))
{
Bitmap bmp = await download.TimeoutAfter(3000);
pictureBox.Image = bmp;
status.Text = “Downloaded”;
}
else
{
pictureBox.Image = null;
status.Text = “Timed out”;
download.ContinueWith(t => Trace(“Task finally completed”));
}
}
finally { btnDownload.Enabled = true; }
}
让我困惑的是这一行:
Bitmap bmp = await download.TimeoutAfter(3000);
逻辑上此时的 TimeoutAfter 有什么意义?这不应该已经通过调用 Task.WhenAny 完成了吗?好像是在说“下载任务完成后,再给它3秒完成”。这是示例中的错误还是我误解了它?