Question

I'm reading through the TAP Whitepaper, and am confused by this sample given for implementing a timeout on page 22:

"Consider a UI application which wants to download an image and disable the UI while the image is downloading. If the download takes too long, however, the UI should be re-enabled and the download should be discarded."

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

What confuses me is this line:

Bitmap bmp = await download.TimeoutAfter(3000);

What is the point of the TimeoutAfter at this point in the logic? Shouldn't this have already been accomplished via the call to Task.WhenAny? It seems like what it is saying is, "After the download task has finished, give it 3 more seconds to finish." Is this an error in the example or am I misunderstanding it?

Was it helpful?

Solution

If the Task.WhenAny returns the "download" it means that the GetBitmapAsync returned without timing out.

The "await download.TimeoutAfter(3000)" ensures that getting the value out of the Task doesn't take too long. It doesn't give an additional 3s.

It would seem difficult to imagine how getting the result after the initially task completes would take a long time.

It could be replaced with:

Bitmap bmp = download.Value;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top