[英]HttpClient await postasync never returns a result
我正在尝试编写代码来发送一个发布请求,在该请求中我上传了一些要在 PHP 中处理的文件。 PHP 代码工作正常(我已经通过浏览器使用真正的 HTML 表单进行了测试)
这就是我调用发生冻结的方法的方式:
private void button2_Click(object sender, EventArgs e)
{
var res = UploadFiles(files_to_upload);
if ( res.Result == true )
{
files_to_upload.Clear();
}
}
方法:
private async Task<bool> UploadFiles(List<UploadingFile_t> files)
{
using (HttpClient client = new HttpClient())
using (MultipartFormDataContent formData = new MultipartFormDataContent())
{
for (int i = 0; i < files_to_upload.Count; i++)
{
UploadingFile_t file = files_to_upload[i];
formData.Add(new StringContent(Path.GetFileName(file.name)), "filename" + i + 1);
formData.Add(file.fileStream, "filedata" + 1 + i);
}
HttpResponseMessage response = null;
try
{
client.BaseAddress = new Uri("http://" + Properties.Settings.Default.host);
client.Timeout = TimeSpan.FromSeconds(10);
string url = "/" + Properties.Settings.Default.host_panel_dir + "/upload_files.php";
response = client.PostAsync(url, formData).Result;
response.EnsureSuccessStatusCode();
client.Dispose();
}
catch (HttpRequestException ex)
{
MessageBox.Show(ex.Message);
return false;
}
if (response.Content.ToString().Contains("UPLSCC") == false)
{
return true;
}
else
{
return false;
}
}
}
代码在等待时冻结 client.PostAsync(url, formData); 或者当我尝试访问结果时(如果我不“等待”电话)。 它从不返回任何结果。
我已经阅读了十几篇具有相同或相同问题的帖子,但似乎没有一个对我有帮助。
我尝试将超时时间设置为 10 秒,看看它是否返回任何错误。 返回的错误是System.AggregateException :发生了一个或多个错误。 TaskCanceledException 的内部异常。
如果需要,我可以发布更多代码
通过调用Result
您正在阻塞主线程,这可能导致死锁。
将您的处理程序更改为async void
并改用await
。
private async void button2_Click(object sender, EventArgs e)
{
var res = await UploadFiles(files_to_upload);
if ( res == true )
{
files_to_upload.Clear();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.