I am writing a parser and faced such a problem. In the absence of an Internet connection, a program that logically crashes, or when the server does not respond in time.

public string WebsiteToString(string url) { try { WebClient wc = new WebClient(); wc.Headers["User-Agent"] = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1"; html = wc.DownloadString(url); } catch { MessageBox.Show("Проблемы с интернетом"); } return html; } 

How can I add in this construction that the program itself in 5 minutes try again to get the data?

  • And what should the program do during these five minutes? And the message about the lack of access need to be issued every 5 minutes? - VladD
  • @VladD can be so if the Internet breaks off, it waits a minute and then tries again if there is no Internet again, it waits a minute again and tries again and so on - shatoidil
  • I understood this, and when to issue a message? - VladD
  • Well, let him give out for the fifth time - shatoidil

1 answer 1

Try something like this:

 async Task<string> CheckWebsiteContentUntilSuccess(string url) { const int nRetriesUntilReport = 5; int currentRetry = nRetriesUntilReport; while (true) { try { WebClient wc = new WebClient(); wc.Headers["User-Agent"] = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1"; return wc.DownloadString(url); } catch (WebException) // ловить всё неправильно { currentRetry--; if (currentRetry == 0) { MessageBox.Show("Проблемы с интернетом"); currentRetry = nRetriesUntilReport; } } await Task.Delay(TimeSpan.FromMinutes(1)); } } 
  • Tell me how can I call this function in code? - shatoidil
  • @shatoidil: Counter question: what should you do with the loaded content? - VladD
  • Transfer to another method that will parse the contents - shatoidil
  • one
    Okay, then the call is most likely some such: StartParsingTask() with async void StartPasringTask() { var html = await CheckWebsiteContentUntilSuccess(url); await Task.Run(() => ParseAndSaveToDB(html)); } async void StartPasringTask() { var html = await CheckWebsiteContentUntilSuccess(url); await Task.Run(() => ParseAndSaveToDB(html)); } async void StartPasringTask() { var html = await CheckWebsiteContentUntilSuccess(url); await Task.Run(() => ParseAndSaveToDB(html)); } . - VladD
  • one
    @shatoidil: Please, glad that helped! - VladD