【问题标题】:How to manage AggregateException is throwing while PostAsync call?PostAsync 调用时如何管理 AggregateException 正在抛出?
【发布时间】:2016-08-01 19:08:36
【问题描述】:

我在 client.PostAsyc 调用时收到 AggregateException,即使我设置了很长的超时时间。

这是我的代码。

try
{
    StoresList objlist = new StoresList();
    Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    Windows.Storage.ApplicationDataContainer session = Windows.Storage.ApplicationData.Current.RoamingSettings;

    var contents = new FormUrlEncodedContent(new[] 
        {
            new KeyValuePair<string, string>("userapi", session.Values["userapi"].ToString()),
            new KeyValuePair<string, string>("keyapi", session.Values["keyapi"].ToString()),
            new KeyValuePair<string, string>("notification_flag","1"),                 
            new KeyValuePair<string, string>("token", localSettings.Values["deviceid"].ToString()),
        });

    using (var client = new HttpClient()  { Timeout = TimeSpan.FromMinutes(4) } )
    {
        var result = client.PostAsync(session.Values["URL"] + "/abcd/", contents).Result;

        if (result.IsSuccessStatusCode)
        {
            string data = result.Content.ReadAsStringAsync().Result;
            if (data.Contains("activate") || data.Contains("enable"))
            {
                //Please activate the Mobile Assistant Extension 
                return null;
            }

            if (data != null)
            {
                List<Stores> objStores = JsonConvert.DeserializeObject<LoginResponse>(data).stores;

                foreach (var item in objStores)
                {
                    Stores objs = new Stores();
                    {
                        objs.id = item.id;
                        objs.name = item.name;
                        objlist.Add(objs);
                    }
                }
            }

        }
    }
    return objlist;
}
catch (Exception ex)
{
    throw ex;
    return null;
}

有人可以建议如何管理吗?有时我会得到 AggregateException。

我已经参考了以下链接,但仍然出现错误。事件我已设置超时。

How can I tell when HttpClient has timed out?

AggregateException is throwing while waiting for PostAsJsonAsync

Whats the difference between HttpClient.Timeout and using the WebRequestHandler timeout properties?

【问题讨论】:

    标签: c# timeout dotnet-httpclient


    【解决方案1】:

    async 添加到您的方法定义中并使用await 而不是.Result

    使用 .Result 会阻塞线程,您将失去使用 Async 方法的所有好处。

    使用await“解包”不仅可以解包数据,还可以解包异常(因此您将得到一个实际异常而不是 AggregateException)。

    var result = await client.PostAsync(session.Values["URL"] + "/abcd/", contents);
    
    ...
    
    string data = await result.Content.ReadAsStringAsync();
    

    有点长,但是这里有一个关于使用 async/await 的好视频:https://channel9.msdn.com/Events/aspConf/aspConf/Async-in-ASP-NET

    值得一看。

    【讨论】:

      【解决方案2】:

      AggregateException 是执行异步任务时遇到的所有异常的集合。

      如果您只想检查遇到的异常而不做任何处理,您可以执行以下操作:

      catch (AggregateException ae)
      {
          // This will just throw the first exception, which might not explain everything/show the entire trace.
          throw ae.InnerException
      }
      

      catch (AggregateException ae)
      {
          // This will flatten the entire exception stack to a string.
          throw new Exception(ae.ToString())
      }
      

      【讨论】:

        猜你喜欢
        • 2013-05-27
        • 1970-01-01
        • 1970-01-01
        • 2011-03-02
        • 2012-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-20
        相关资源
        最近更新 更多