Intermittent errors while de-serializing object from XML

前端 未结 4 2196
面向向阳花
面向向阳花 2021-02-09 02:30

I have a program that takes objects stored as XML in a database (basicly a message queue) and de-serializes them. Intermittently, I will get one of the following errors:

<
4条回答
  •  日久生厌
    2021-02-09 03:02

    XmlSerializer is supposed to be thread safe.

    Even if that's the case, you can notice the behavior you are getting is in both cases failing at: XmlSerializer..ctor(Type type)

    Given that, it seriously look like a multi-threading limitation trying to create serializers.

    I suggest to take this code you have:

    public XmlSerializer GetSerializer(Type t) {
            if (!SerializerCache.ContainsKey(t.FullName)) {
                SerializerCache.Add(t.FullName, new XmlSerializer(t)); // Error occurs here, intermittently
            }
            return SerializerCache[t.FullName];
        }
    

    And implement a lock on the Add. This way you are only creating 1 serializer at a time. The hit is small if you aren't processing tons of different types.

    Note that you need the lock anyway, as the way it is you could get duplicate exceptions when 2 types try to be added at the same time.

    static object serializerCacheLock = new object();
    public XmlSerializer GetSerializer(Type t) {
            if (!SerializerCache.ContainsKey(t.FullName))
            lock(serializerCacheLock)
            if (!SerializerCache.ContainsKey(t.FullName)) {
                SerializerCache.Add(t.FullName, new XmlSerializer(t));
            }
            return SerializerCache[t.FullName];
        }
    

    If the above still isn't enough, I'd try with a read/write lock on serializer constructor vs. serializers usage. Line of thought being that maybe the multi-threading issue is worth than 2 ctors running at the same time.

    All above is a Huge guess, but if it were me I'd definitely confirm is not that.

提交回复
热议问题