0

I have a web site that connect to web service to database

I have this inconsistent error that says

{"Message":"Collection was modified; enumeration operation may not execute.","StackTrace":" at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)\r\n at System.Collections.Generic.List1.Enumerator.MoveNextRare()\r\n at System.Collections.Generic.List1.Enumerator.MoveNext()\r\n at System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n at 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

I have these code at the c# web service, this function may return 0 or more rows.

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;
    }

the source of error is inconsistent. I have these in my 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);
        }

    });
}

I hope someone will help me. I've been banging my head for hours now

Vian Ojeda Garcia
  • 827
  • 4
  • 17
  • 34
  • Seems be related to concurrent calls, while the static variable _get_liked is serializing, another call tries to manipulate it. – mehran Nov 29 '17 at 02:54

1 Answers1

3

You return static list that code modifies on every request. This code is expected to behave erratically when more than one request runs in parallel. In particular it should fail with error you see when response is serialized and list is .Clear() at the same time by another request.

Fix - return new list every time instead of return _get_liked and remove _get_liked completely from your code:

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

In general using static is at least discouraged in web apps - see Scope of static Variable in multi-user ASP.NET web application for example.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179