我是异步编程的新手,正在尝试将 2 个文件并行上传到 rest api。每个文件的上传过程包括 3 个 rest 调用 1. 初始放置:创建文件 2. 使用补丁追加数据 3. 保存/刷新文件中的数据以提交它。
所有这些都是按顺序进行的,但是当我尝试异步执行时,我会随机失败,因为异步方法的参数会被其他任务覆盖。
我一直在关注这里的指南:https ://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/并尝试遵循类似的策略
private async Task<string> UploadFiles(string year, string month, string filename, string accesstoken, string path)
{
//Initial Put : corresponding to point 1 above in the summary
var method = new HttpMethod("PUT");
url = String.Format("https://someurl/part1/{0}/{1}/{2}?resource=file&recursive=True", year, month, localfilename);
var request = new HttpRequestMessage(method, url)
{
Content = null
};
request.Headers.Add("Authorization", "Bearer " + accesstoken);
var initput = await client.SendAsync(request);
//Append Data :corresponding to point 2 above in the summary
url = String.Format("https://someurl/part1/{0}/{1}/{2}?action=append&position=0", year, month, localfilename);
****Here some code for file details which isn't necessary for this question***
method = new HttpMethod("PATCH");
request = new HttpRequestMessage(method, url)
{
Content = content
};
request.Headers.Add("Authorization", "Bearer " + accesstoken);
var response = await client.SendAsync(request);
long? position = request.Content.Headers.ContentLength;
//Flush Data:corresponding to point 3 above in the summary
url = String.Format("someurl/part1/{0}/{1}/{2}?action=flush&position={3}", year, month, localfilename, position.ToString());
request = new HttpRequestMessage(method, url)
{
Content = null
};
}
精慕HU
相关分类