【问题标题】:Inconsistent error: collection was modified enumeration operation may not execute不一致的错误:集合被修改枚举操作可能无法执行
【发布时间】:2017-11-29 02:50:33
【问题描述】:

我有一个网站连接到数据库的网络服务

我有这个不一致的错误说

{"Message":"集合已修改;枚举操作可能无法执行。","StackTrace":" at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)\r\n at System.Collections.Generic.List@987654321 @1.Enumerator.MoveNext()\r\n 在 System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)\r\n 在 System.Web.Script .Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n 在 System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth , Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n 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);
        }

    });
}

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

【问题讨论】:

  • 似乎与并发调用有关,而静态变量_get_liked正在序列化,另一个调用试图对其进行操作。

标签: javascript c# .net serialization


【解决方案1】:

您返回静态列表,代码会根据每个请求进行修改。当多个请求并行运行时,此代码预计会出现异常行为。特别是当响应被序列化并且列表是 .Clear() 同时被另一个请求时,它应该会失败并出现错误。

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

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

一般来说,至少不鼓励在网络应用程序中使用static - 例如,请参阅Scope of static Variable in multi-user ASP.NET web application

【讨论】:

  • 尝试了您的解决方案,它运行良好。但是有没有更清洁的方法来使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多