任务已取消Xamarin异常

时间:2018-11-14 01:27:50

标签: xamarin xamarin.forms

我的 PostAsync 中收到“ 任务被取消的例外情况”。这是什么原因?我怎样才能解决这个问题?我研究了他们认为是由于超时导致的可能原因。如果是这样,如何延长超时时间?如果没有,可能的解决方法是什么?

try
{
    string url = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Request=Fsq6Tr";
    string contentType = "application/json";
    JObject json = new JObject
    {
        { "CAF", caf },
        { "CustomerID", retailerCode },
        { "EmployeeNumber", employeeNumber },
        { "Street", street },
        { "Barangay", barangay },
        { "Town", town },
        { "District", district },
        { "Province", province },
        { "Country", country },
        { "Landmark", landmark },
        { "Telephone1", telephone1 },
        { "Telephone2", telephone2 },
        { "Mobile", mobile },
        { "Email", email },
        { "Location", location },
        { "Date", Convert.ToDateTime(date) },
        { "StartTime", Convert.ToDateTime(startTime) },
        { "EndTime", Convert.ToDateTime(endTime) },
        { "Photo1", photo1 },
        { "Photo2", photo2 },
        { "Photo3", photo3 },
        { "Video", video },
        { "MobilePhoto1", photo1url },
        { "MobilePhoto2", photo2url },
        { "MobilePhoto3", photo3url },
        { "MobileVideo", videourl },
        { "Rekorida", rekorida },
        { "Merchandizing", merchandizing },
        { "TradeCheck", tradecheck },
        { "Others", others },
        { "OtherConcern", otherconcern },
        { "Remarks", remarks },
        { "LastSync", Convert.ToDateTime(current_datetime) },
        { "MobileUpdate", Convert.ToDateTime(current_datetime) }
   };

   HttpClient client = new HttpClient();
   var response = await client.PostAsync(url, new StringContent(json.ToString(), Encoding.UTF8, contentType));

    await DisplayAlert("Success!", "Form sent successfully!", "Got it");
   }
   catch (Exception ex)
   {
         await DisplayAlert(" Sending Error ", ex.Message, "Got it");
   }

2 个答案:

答案 0 :(得分:1)

是的,奇怪的是HttpClient抛出TaskCancelledException来请求超时。这是有关HttpClient超时的不错的博客文章:https://www.thomaslevesque.com/2018/02/25/better-timeout-handling-with-httpclient/

HttpClient确实具有您可以设置的Timeout属性:https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?redirectedfrom=MSDN&view=netframework-4.7.2

要为使用该HttpClient的所有请求设置超时:

HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(200); // this is double the default

也就是说,最好找出为什么您的请求需要100秒钟以上才能完成。信号不好?服务器工作过度并响应缓慢? Web请求可能很慢的原因有很多。

答案 1 :(得分:1)

我超时的原因是因为设备具有节能模式,并且它阻止了后台连接。也许可以帮助某人...