我是异步编程的新手,正在尝试将 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 }; }
1 回答
精慕HU
TA贡献1845条经验 获得超8个赞
您对 url 变量的使用不是线程安全的。我看到它是在您的方法之外定义的,但是您随后使用它并在整个方法中对其进行了更改。
当您有两个异步运行时,使用和更改相同的变量会出现竞争条件。
- 1 回答
- 0 关注
- 74 浏览
添加回答
举报
0/150
提交
取消