[英]why is this webclient post code not being timed out when there is no network connection?
我的xamarin.ios
應用程序中有這個 function,該應用程序將 object 發布到我的 Z8A5DA52ED1205721C. object 包含字符串和 1 個成員作為 base64 字符串。 當沒有連接時,我似乎無法在不到 5 分鍾的時間內獲得超時並獲得異常。 但是,當 object 中沒有基數 64 時,它似乎超時了。 有什么想法可以讓它發揮作用嗎? 這是我的代碼:
public static string postData(object @params, string url)
{
MyWeWbClient webClient = new MyWeWbClient();
try
{
webClient.Headers["content-type"] = "application/json";
webClient.Headers.Add("Authorization", "Bearer " + Settings.GeneralSettings3);
var reqString = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@params, Formatting.Indented));
byte[] resByte = webClient.UploadData(url, "post", reqString);
var resString1 = Encoding.Default.GetString(resByte);
webClient.Dispose();
return resString1;
}
catch (WebException ex)
{
string responseText = "";
var responseStream = ex.Response?.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseText = reader.ReadToEnd();
}
}
throw new Exception(responseText.ToString());
}catch(Exception ex)
{
throw;
}
}
還有我的自定義網絡客戶端 class 所以我可以設置超時:
public class MyWeWbClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;//20 * 60 * 1000;
return w;
}
}
提前致謝。 任何幫助表示贊賞。
編輯:
相同的代碼在xamarin.android
上運行良好,如果沒有預期的互聯網連接,它會超時。
我不建議使用 webClient,我會使用像 restsharp 這樣的外部依賴。
或者,您可以使用Task.Run()
對其進行硬編碼,但由於它在 Xamarin 中,我不能說。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.