The DownloadStringAsync method uses an event model, raising the DownloadStringCompleted when it has finished. You can also stop the request if it is taking too long by calling WebClient.CancelAsync()
. This will let your main request thread and your WebClient thread to run in parallel, and allow you to decide exactly how long you want your main thread to wait before returning.
In the example below, we initiate the download and set the event handler we want invoked when it is finished. The DownloadStringAsync returns immediately, so we can continue processing the rest of our request.
To demonstrate a more granular control over this operation, when we reach the end of our controller action, we can check to see if the download is complete yet; if not, give it 3 more seconds and then abort.
string downloadString = null;
ActionResult MyAction()
{
//get the download location
WebClient client = StartDownload(uri);
//do other stuff
CheckAndFinalizeDownload(client);
client.Dispose();
}
WebClient StartDownload(Uri uri)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Download_Completed);
client.DownloadStringAsync(uri);
return client;
}
void CheckAndFinalizeDownload(WebClient client)
{
if(this.downloadString == null)
{
Thread.Sleep(3000);
}
if(this.downloadString == null)
{
client.CancelAsync();
this.downloadString = string.Empty;
}
}
void Download_Completed(object sender, DownloadStringCompletedEventArgs e)
{
if(!e.Cancelled && e.Error == null)
{
this.downloadString = (string)e.Result;
}
}