我有一些要上传的文件,有些文件失败了,因为帖子是异步的而不是同步的。
我试图将此通话设为同步通话..
我想等待回复。
如何将此调用设为同步?
static async Task<JObect> Upload(string key, string url, string
sourceFile, string targetFormat)
{
using (HttpClientHandler handler = new HttpClientHandler {
Credentials = new NetworkCredential(key, "")
})
using (HttpClient client = new HttpClient(handler))
{
var request = new MultipartFormDataContent();
request.Add(new StringContent(targetFormat), "target_format");
request.Add(new StreamContent(File.OpenRead(sourceFile)),
"source_file",
new FileInfo(sourceFile).Name);
using (HttpResponseMessage response = await client.PostAsync(url,
request).ConfigureAwait(false))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync().ConfigureAwait(false);
return JsonObject.Parse(data);
}
}
}
任何帮助表示赞赏!
答案 0 :(得分:47)
更改
await content.ReadAsStringAsync().ConfigureAwait(false)
到
content.ReadAsStringAsync().Result
ReadAsStringAsync返回一个Task对象。 &#39; .Result&#39;在行的末尾告诉编译器返回内部字符串。
答案 1 :(得分:1)
应该这样做:
static async Task<JObect> Upload(string key, string url, string
sourceFile, string targetFormat)
{
using (HttpClientHandler handler = new HttpClientHandler {
Credentials = new NetworkCredential(key, "")
})
using (HttpClient client = new HttpClient(handler))
{
var request = new MultipartFormDataContent();
request.Add(new StringContent(targetFormat), "target_format");
request.Add(new StreamContent(File.OpenRead(sourceFile)),
"source_file",
new FileInfo(sourceFile).Name);
using (HttpResponseMessage response = await client.PostAsync(url,request))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
return JsonObject.Parse(data);
}
}
}