0条评论
还没有人评论过~
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
应该这么写
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());