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行值是重复的,这怎么改呢?
本地变量引起的问题。
你的代码,没复制完整吧?在foreach过程中,json是不断的改变吧?
参考第一个示例:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.taskfactory.startnew
代码没有完整,核心就这个,上面的循环调用下面的,Json是每条都不一样的。
@happydaily: 所以task还没启动,循环中的json已经变好好几回了,等task开始执行了,就会存在几个task拿到一样的json。照msdn上的示例一修改你的代码就可以了
@pencile: 原来是这么回事,谢谢。
应该这么写
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());
不行不行,这个代码更坑-_-,原来最多一条重复两次,用了这个代码最多一条重复了几十次。
@happydaily: 好吧,😂
那我建议不要定义json,而是把那个拼接的string直接当参数传入,我就不信还会重复。
@Shendu.CC: 这个不拼接怎么办呢,循环的目的就是为了生成不同的JSON啊
@happydaily:
Task.Run(()=>HttpHelperSync.UpdatePositionSync("{\"id\":\"" + po.Key_Id + "\",\"name\":\"" + po.Value + "\",\"remark\":\"" + po.Comments + "\"}",servername)));
@happydaily:感觉这样改也不行,还是按照楼下的解决方案吧。StartNew