Reputation: 2285
I am getting AggregateException while client.PostAsyc call even I have set long timeout.
Here is my code.
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;
}
Can anybody suggest how to manage this? Sometime I get AggregateException.
I have referred following link but I still get error. Event I have set timeout.
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?
Upvotes: 2
Views: 3953
Reputation: 40988
Add async
to your method definition and use await
instead of .Result
.
Using .Result
blocks the thread and you lose all the benfits of using the Async methods.
Using await
"unwraps" not only the data, but the exceptions too (so you will get an actual exception rather than AggregateException).
var result = await client.PostAsync(session.Values["URL"] + "/abcd/", contents);
...
string data = await result.Content.ReadAsStringAsync();
Upvotes: 5
Reputation: 486
AggregateException is a collection of all exceptions encountered while doing an async task.
If you just want to check what the exception encountered was without doing any handling, you can do something like:
catch (AggregateException ae)
{
// This will just throw the first exception, which might not explain everything/show the entire trace.
throw ae.InnerException
}
or
catch (AggregateException ae)
{
// This will flatten the entire exception stack to a string.
throw new Exception(ae.ToString())
}
Upvotes: 0