[英]HttpClient await postasync never returns a result
I am trying to write code to send a post request where I upload some files to be handled in PHP.我正在尝试编写代码来发送一个发布请求,在该请求中我上传了一些要在 PHP 中处理的文件。 the PHP code is working correctly (I've tested via browser with a real HTML form) PHP 代码工作正常(我已经通过浏览器使用真正的 HTML 表单进行了测试)
This is how im calling the method where the freezing occurs:这就是我调用发生冻结的方法的方式:
private void button2_Click(object sender, EventArgs e)
{
var res = UploadFiles(files_to_upload);
if ( res.Result == true )
{
files_to_upload.Clear();
}
}
The method:方法:
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;
}
}
}
The code is freezing at the await client.PostAsync(url, formData);代码在等待时冻结 client.PostAsync(url, formData); or when i try to access the result (if I dont "await" the call).或者当我尝试访问结果时(如果我不“等待”电话)。 It never returns any result.它从不返回任何结果。
I've read a dozen of posts with the same or identical problems and none of them seem to helped me.我已经阅读了十几篇具有相同或相同问题的帖子,但似乎没有一个对我有帮助。
I've tried setting a timeout time at 10 seconds, to see if it returns any errors.我尝试将超时时间设置为 10 秒,看看它是否返回任何错误。 The returned error was a System.AggregateException : one or more errors occurred.返回的错误是System.AggregateException :发生了一个或多个错误。 With the inner exception of TaskCanceledException. TaskCanceledException 的内部异常。
I can post more code if needed如果需要,我可以发布更多代码
By calling Result
you are blocking the main thread, which could result in a deadlock.通过调用Result
您正在阻塞主线程,这可能导致死锁。
Change your handler to async void
and use await
instead.将您的处理程序更改为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.