Intermittent errors while de-serializing object from XML

前端 未结 4 2190
面向向阳花
面向向阳花 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 02:53

    This is a sign that you are not caching your serialisers which is not good at all => it leads to memory leak and I suspect you will experience this.

    Remember that .NET generates code and compiles them into assemblies every time you create a serialiser.

    Always create your serialisers and then cache them.

    Here is a sample:

    public class SerialiserCache
    {
    
        private static readonly SerialiserCache _current = new SerialiserCache();
        private Dictionary _cache = new Dictionary();
    
        private SerialiserCache()
        {
    
        }
    
        public static SerialiserCache Current
        {
            get { return _current; }
        }
    
        public XmlSerializer this[Type t]
        {
            get
            {
                LoadIfNecessary(t);
                return _cache[t];
            }
        }
    
        private void LoadIfNecessary(Type t)
        {
    
            // double if to prevent race conditions 
            if (!_cache.ContainsKey(t))
            {
                lock (_cache)
                {
                    if (!_cache.ContainsKey(t))
                    {
                        _cache[t] = new XmlSerializer(typeof(T));
                    }
                }
            }
        }
    
    }
    

提交回复
热议问题