HttpClient,multipartdatacontent:如果发送大于100k的文件,则“任务被取消”异常

时间:2018-01-10 06:58:54

标签: c# .net xamarin httpclient

我使用以下功能将文件上传到服务器:

private async void SendRequest(string url, string content)
{
    HttpClient httpClient = new HttpClient();
    httpClient.Timeout = new TimeSpan(0, 0, 5, 0);
    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
    requestMessage.Headers.ExpectContinue = false;
    MultipartFormDataContent multiPartContent = new MultipartFormDataContent("PartContent");
    StringContent stringContent = new StringContent(content, System.Text.Encoding.UTF8, "application/json");
    multiPartContent.Add(stringContent, "NoiDung");
    if (tbAttachment.Text.Length > 0)
    {
        foreach (string filefullpath in openFileDialog1.FileNames)
        {
            FileInfo fi = new FileInfo(filefullpath);
            string filename = fi.Name;
            byte[] filecontent = File.ReadAllBytes(filefullpath);
            HttpContent content = new ByteArrayContent(filecontent);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            multiPartContent.Add(content, filename, filename);
        }                        
    }
    requestMessage.Content = multiPartContent;
    HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead);
    string result = await httpResponseMessage.Content.ReadAsStringAsync();
}

如果上传文件的总大小小于120KB,则此功能运行正常;如果上传文件在运行约5分钟后大于120KB,则该函数将抛出TaskCanceledException

异常转储是:

System.Threading.Tasks.TaskCanceledException: A task was canceled.    
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at TestServices.ServiceTestForm2.<BtnSend_Click>d__52.MoveNext() in C:\Users\linhdh\source\repos\TestServices\TestServices\ServiceTestForm2.cs:line 469

使用multipartcontent上传文件的最佳方法是什么?是否有任何服务器端设置来修复此错误?

1 个答案:

答案 0 :(得分:0)

如果你得到一个&#34;任务被取消&#34;从异步代码中,您必须检查代码中是否抛出了特定的(如果有的话)异常。甚至可能在主线上再次提起它。

吞咽异常是异常处理的致命罪。大多数情况下,您必须编写代码才能实现它。但是使用多线程和多任务处理,吞咽异常会自动发生。实际上你必须编写代码来避免它。一旦你知道任务中究竟发生了什么,你就可以看看如何修复它。

以下是两篇关于正当例外的文章,我建议每个程序员阅读:

你所拥有的可能是外生的或愚蠢的例外。