I'm trying to upload a file to the server. Once the user take the photo with the app and accept it, the photo its uploaded. But if the use choose to take another photo while the previous photo is being still uploading, the uploading process gets cancel and throws a AggregateException
. I need to upload more than one to avoid that kind of scenario.
Here the code that i use to upload the file:
private async Task<T> ExecuteHttpPost<T>(string url, HttpContent content) where T : BaseServerResponseModel
{
try
{
using (HttpClient client = new HttpClient())
{
HttpStatusCode statusCode = HttpStatusCode.OK;
if (BeforeRequestPerformListener != null)
{
if (!BeforeRequestPerformListener(this, new BeforeRequestEventArgs(url, null)))
{
return null;
}
}
var response = await client.PostAsync(url, content);
if (ResponseRecivedListener != null)
{
ResponseRecivedListener(this, response);
}
statusCode = response.StatusCode;
response.EnsureSuccessStatusCode();
var entityResponse = await response.GetJsonResponse<T>();
entityResponse.ThrowIfNoSuccess();
return entityResponse;
}
}
catch (Exception e)
{
throw;
}
return null;
}
I also tried to wrap the whole code into a Task.Run
but still throwing the same exception.
Anything that I'm missing?
Side note: the photo indeed gets uploaded to the server if I wait for it to finish. Its only when I open the camera while uploading that the exception occur
There are multiple scenarios where such file uploads can be canceled. In fact, taking another picture is just one. You should also consider lifecycle events such as spontaneous suspension and termination of your app.
To create a more robust environment for these sensitive server communications you should consider delegating your file upload to a background task. A background task will continue running, even if your app is terminated (*) or - like in your case - the user decides to do something different.
The most simple approach would be using a background transfer.
Overview: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh452975(v=win.10).aspx Upload sample code: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj152727.aspx
This should do the trick for you. However if you need a more sophisticated solution you could write yourself a background task that processes your upload queue and notifies the foreground app on status updates such as progress and completion.
Quickstart: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx How to monitor progress and completion: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977054.aspx
(*) There are performance restrictions for background tasks as well.