不一致错误:收集已修改枚举操作可能无法执行



我有一个连接到数据库的Web服务

的网站我有这个不一致的错误,说

{"消息":"集合已修改;枚举操作可能无法执行。","StackTrace":" at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)\r at System.Collections.Generic.List1.Enumerator.MoveNextRare()rn at System.Collections.Generic.List1.Enumerator.MoveNext()\r at System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)\r at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, Str

我在 c# Web 服务中有这些代码,此函数可能会返回 0 行或更多行。

public class Liked
{
public bool liked;
}
static List<Liked> _get_liked = new List<Liked> { };
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public List<Liked> get_liked(string userID,string postID)
{
DataTable table = null;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Like_Retrieve";
cmd.Parameters.AddWithValue("@UserId", userID);
cmd.Parameters.AddWithValue("@PostId", postID);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
table = this.dbcon.ExecuteDataTable(cmd);
_get_liked.Clear();
Liked _list = new Liked();
if (table.Rows.Count > 0)
{            
_list.liked = true;      
}
else
{
_list.liked = false;
}
_get_liked.Add(_list);
return _get_liked;
}

错误来源不一致。我的JavaScript中有这些

function checkLike(userId, postId) {
$.ajax({
type: "POST",
url: "../Main.asmx/get_liked",
data: "{'userID':'" + userId + "', 'postID':'" + postId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = response.d;
$.each(result, function (index,data) {
var liked = data.liked;
if (liked == true) {
$("#" + postId).prev().parent("button").css("background", "#ccc");
}
else
{
$("#" + postId).prev().parent("button").css("background", "white");
}
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error');
console.log(postId);
console.log(userId);
console.log(xhr.responseText);
console.log(thrownError);
}
});
}

我希望有人能帮助我。我已经撞了几个小时了

返回静态列表,代码在每个请求上修改该列表。当多个请求并行运行时,此代码的行为应不稳定。特别是,当响应被序列化并且列表同时被另一个请求.Clear()时,它应该失败并出现错误。

修复 - 每次都返回新列表而不是return _get_liked并从代码中完全删除_get_liked

return new List<Liked> { 
new Liked { liked = table.Rows.Count > 0 }
};

通常,至少不鼓励在 Web 应用程序中使用static- 例如,请参阅多用户 ASP.NET Web 应用程序中静态变量的范围。

最新更新