亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有從多個任務調用的參數的異步方法會導致沖突

具有從多個任務調用的參數的異步方法會導致沖突

C#
慕婉清6462132 2022-12-31 11:08:41
我是異步編程的新手,正在嘗試將 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 變量的使用不是線程安全的。我看到它是在您的方法之外定義的,但是您隨后使用它并在整個方法中對其進行了更改。

當您有兩個異步運行時,使用和更改相同的變量會出現競爭條件。


查看完整回答
反對 回復 2022-12-31
  • 1 回答
  • 0 關注
  • 93 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號