使用多个任务调用的参数的异步方法会导致冲突

问题描述 投票:0回答:1

我是异步编程的新手,我试图将2个文件并行上传到rest api。每个文件的上载过程包括3个休息调用1.初始放置:创建文件2.使用Patch 3附加数据。保存/刷新文件中的数据以提交它。

所有这些都按顺序工作,但是当我尝试异步执行时,我会得到随机故障,因为异步方法的参数会被其他任务覆盖。

我一直在这里遵循指南:https://docs.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
            };

            request.Headers.Add("Authorization", "Bearer " + accesstoken);


            response = await client.SendAsync(request);

            return filename;

        }

在调用者中,我使用多个任务调用它,以便它们同时启动然后等待

            Task<string> uploadCounterpartFileTask = UploadFiles(year, month, filename_counterparts, accesstoken, path);
            Task<string> uploadProductCategoryFileTask = UploadFiles(year, month, filename_productcategories, accesstoken, path);

            var allTasks = new List<System.Threading.Tasks.Task> { uploadCounterpartFileTask, uploadProductCategoryFileTask };


            while (allTasks.Any())
            {
                System.Threading.Tasks.Task finished = await System.Threading.Tasks.Task.WhenAny(allTasks);
                if (finished == uploadCounterpartFileTask)
                {
                    allTasks.Remove(uploadCounterpartFileTask);
                    var counterpartFile = await uploadCounterpartFileTask;
                }
                else if (finished == uploadProductCategoryFileTask)
                {
                    allTasks.Remove(uploadProductCategoryFileTask);
                    var productCategoriesFile = await uploadProductCategoryFileTask;
                }
            }

我期待这一点(虽然没有按任何特定顺序排列,但在特定文件中排序或在任务中排序)。

所以,如果我查看Fiddler,我希望:

/part1/2019/02/Counterparts.avro?resource=file&recursive=True
/part1/2019/02/ProductCategories.avro?resource=file&recursive=True
/part1/2019/02/ProductCategories.avro?action=append&position=0
/part1/2019/02/Counterparts.avro?action=append&position=0
/part1/2019/02/ProductCategories.avro?action=flush&position=1664
/part1/2019/02/Counterparts.avro?action=flush&position=30907958

但我得到:

/part1/2019/02/Counterparts.avro?resource=file&recursive=True
/part1/2019/02/ProductCategories.avro?resource=file&recursive=True
/part1/2019/02/Counterparts.avro?action=append&position=0
/part1/2019/02/Counterparts.avro?action=append&position=0
/part1/2019/02/ProductCategories.avro?action=flush&position=1664
/part1/2019/02/Counterparts.avro?action=flush&position=30907958

因此,如果您看到“action = append”,我会收到2次调用Counterparts而不是ProductCategories,因此ProductCategories上的flush操作失败,因为它没有首先发生追加。

基本上发生的事情是我的异步函数中的参数文件名被覆盖在任务中。

如何确保2个文件并行运行这3个REST调用,而不会覆盖其他任务中的变量

c# asynchronous async-await
1个回答
2
投票

您对url变量的使用不是线程安全的。我看到它是在你的方法之外定义的,但是你使用它并在整个方法中改变它。

当您有两个异步运行时,使用和更改相同的变量可以获得竞争条件。

© www.soinside.com 2019 - 2024. All rights reserved.