Task异步方法调用出现重复值

2019-08-30 14:47发布

复制代码
public static void TransDutySync(IEnumerable<KeyValueEntity> _Positions, int servername)
        {

            foreach (var po in _Positions)
            {
               string json = "{\"id\":\"" + po.Key_Id + "\",\"name\":\"" + po.Value + "\",\"remark\":\"" + po.Comments + "\"}";       
Thread.Sleep(
30); HttpHelperSync.UpdatePositionSync(json, servername);//同步 Task.Run(() => HttpHelperSync.UpdatePositionSync(json, servername));//异步 } } public static string HttpPostSync(UrlCollection urlCollection) { string json = urlCollection.json; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlCollection.Url); request.Method = "POST"; request.ContentType = "application/json"; request.Headers.Add(HttpRequestHeader.Authorization,"Basic "+ urlCollection.Token); string retString = string.Empty;int StatusCode = 0; try { Stream myRequestStream = request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8")); myStreamWriter.Write(json); myStreamWriter.Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; StatusCode = (int)response.StatusCode; Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); } catch (WebException ex) { retString = ex.Message; HttpWebResponse response = (HttpWebResponse)ex.Response; StatusCode = (int)response.StatusCode; } RECLOUD_DATASYNC_LOG _log = new RECLOUD_DATASYNC_LOG(); _log.LOGTIME = DateTime.Now; _log.LOGTITLE = logTitle; _log.RESPONSECODE = StatusCode; _log.LOGCONTENT = json; _log.RESPONSECONTENT = retString; _log.SERVERNAME = urlCollection.ServerName;//这个值每个请求是一样的 HttpHelper.WriteLog(_log);//写数据库日志 return retString; }
复制代码

 

 

请教一下,如果写成同步方法,是没有问题的,如果写成异步形式,358行更新,数据库中就出现50-70行值是重复的,这怎么改呢?

标签: 异步 task
2条回答
仙女界的扛把子
2楼-- · 2019-08-30 15:33

本地变量引起的问题。
你的代码,没复制完整吧?在foreach过程中,json是不断的改变吧?
参考第一个示例:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.taskfactory.startnew

查看更多
3楼-- · 2019-08-30 15:34

应该这么写

var tasks = new List<Task>();
 foreach (var po in _Positions)
            {
                string json = "{}";
                Thread.Sleep(30);
                //HttpHelperSync.UpdatePositionSync(json, servername);//同步
                //Task.Run(() => HttpHelperSync.UpdatePositionSync(json, servername));//异步
               tasks.Add(Task.Run(() => HttpHelperSync.UpdatePositionSync(json, servername)));
            }
Task.WaitAll(task.ToArray());

查看更多
登录 后发表回答