I'm downloading a string from a webpage using System.Net.WebClient.DownloadStringTaskAsync
asynchronously.
About 4 out of 5 times, this completes successfully, but occasionally, it hangs, and I will have to restart the program to "reset" it.
Thus I'm thinking of implementing a time-out that automatically cancels the Task after 5 seconds and restarts it:
async void DoTasks()
{
string output;
int timeout = 5000;
WebClient client = new WebClient() { Encoding = Encoding.UTF8 };
Task<string> task = client.DownloadStringTaskAsync(url);
if (await Task.WhenAny(task, Task.Delay(timeout)) == task)
{
output = task.Result;
}
else
{
client.CancelAsync();
DoTasks();
}
}
This, however, returns a NullReferenceException
.