【问题标题】:File upload gets cancel when opening the camera打开相机时文件上传被取消
【发布时间】:2015-06-23 19:08:42
【问题描述】:

我正在尝试将文件上传到服务器。一旦用户使用应用程序拍摄照片并接受它,照片就会上传。但是,如果用户在上一张照片仍在上传时选择拍摄另一张照片,则上传过程将被取消并抛出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 中,但仍然抛出相同的异常。

我错过了什么?

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

【问题讨论】:

  • 是的,正好在 await client.PostAsync(url, content)

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


【解决方案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

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

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2012-10-12
    • 2017-03-19
    • 2018-09-08
    • 2019-10-04
    相关资源
    最近更新 更多