I have some code that calls a method to download a file:
private async Task DownloadFile()
{
WebClient client = new WebClient();
var downloadTask =
Task.Run(
() =>
client.DownloadFile("http://www.worldofcats.com/bigkitty.zip",
"c:\\cats\\"
);
await downloadTask;
}
To invoke this method, I do this:
var downloadTask = DownloadFile();
await downloadTask;
Since it's part of a forms app, this causes no issue while it downloads with the UI being unresponsive. The only problem is, the DownloadFile method has no timeout, and sometimes it might go wrong or hang, so I need to put a timeout in.
If I use Task.Wait(x);
then it blocks the UI thread. I think I can possibly use await Task.WhenAny(downloadTask, () => Thread.Sleep(50000));
but I am not sure if this is the best way.
So my question is, what should I do to solve this, and how can I cleanup my task if it's forcibly terminated? (Or do I have to worry about that?)