打开相机时文件上传被取消

时间:2015-06-23 19:08:43

标签: c# camera windows-phone-8.1 task dotnet-httpclient

我正在尝试将文件上传到服务器。一旦用户使用应用程序拍摄照片并接受它,照片就会上传。但是,如果用户选择在上一张照片仍在上传时拍摄另一张照片,则上传过程会被取消并抛出AggregateException。我需要上传多个以避免这种情况。

这是我用来上传文件的代码:

  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;
        }

我还尝试将整个代码包装成Task.Run,但仍然抛出相同的异常。

我缺少什么?

旁注:如果我等待照片完成,照片确实会上传到服务器。只有在我上传相机时才会发生异常

1 个答案:

答案 0 :(得分:1)

有多种情况可以取消此类文件上传。事实上,拍摄另一张照片只是其中之一。您还应该考虑生命周期事件,例如自发暂停和终止您的应用。

要为这些敏感的服务器通信创建更强大的环境,您应该考虑将文件上载委派给后台任务。后台任务将继续运行,即使您的应用已被终止(*)或 - 就像您的情况一样 - 用户决定采取不同的行动。

最简单的方法是使用后台传输。

概述: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh452975(v=win.10).aspx 上传示例代码: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj152727.aspx

这应该可以帮到你。但是,如果您需要更复杂的解决方案,您可以自己编写一个处理上传队列的后台任务,并通知前台应用程序状态更新,例如进度和完成。

快速入门: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx 如何监控进度和完成情况: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977054.aspx

(*)后台任务也有性能限制。