嗨大家即時通訊嘗試創建一個方法,將始終返回一個網址源,如果例如互聯網熄滅它將繼續工作,直到它出現並返回網址源等等,如果還有其他東西發生。到目前爲止在我的方法,當我「關閉」互聯網和「打開它」回程序繼續正常,但我有一個問題時發生超時,我在一個循環中「下降」我知道while(true)是不是正確的做法,但即時通訊用於我的測試。Webrequest不能「逃生」超時
那麼如何跳過超時異常並「重試」我的方法?
public static async Task<string> GetUrlSource(string url)
{
string source = "";
while (true)
{
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
hwr.AllowAutoRedirect = true;
hwr.UserAgent = UserAgent;
hwr.Headers.Add(hd_ac_lang[0], hd_ac_lang[1]);
hwr.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
hwr.Timeout = 14000;
try
{
using (var response = hwr.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
source = await reader.ReadToEndAsync();
if (check_source(source))
{
return source;
}
}
}
}
catch (WebException ex)
{
hwr.Abort();
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttatusCode.NotFound)
{
// handle the 404 here
return "404";
}
}
else
{
Console.WriteLine(ex.Status.ToString());
}
}
}
}
注:我曾經有hwr.Abort();成爲芬蘭條款,但它沒有幫助。
編輯:控制檯每14秒寫一次這條消息,因爲我的超時時間我認爲它與此相關。
你目前的方法有什麼問題?你的超時會導致一個異常,並且你循環回來? – CathalMF
@CathalMF我不知道,但第一次超時後,似乎是在一個循環。它就像之後的那樣永遠處於超時狀態。 – Incognito
你確定它不是你的服務器端正在破壞導致超時循環嗎? – CathalMF