locked
Per call storage in .asmx web service. RRS feed

  • Question

  • User-313978683 posted

    We have an existing .asmx web service that is using a static collection to store errors encountered during form processing.  Unfortunately, as you might have already guessed, this is not thread safe.  Consequently we are looking for a thread safe way to do this.  I would prefer to avoid passing an error object back and forth with every call.  I have currently re-written it to use the HttpContext.Current.Items collection (Asp.Net Compatibility is enabled), but was wondering if anyone could think of a better way to implement this?  Is there some kind of session-state like storage available in a .asmx web service that I am not aware of?

    Thanks in advance!

    -Nathan

    Tuesday, June 18, 2013 4:25 PM

All replies

  • User-313978683 posted

    This is the current implementation for the fix.  Is there a better way I could have done this?

    public class ContextErrorCollection
    {
        public static void AddToErrorCollection(string error)
        {
            var nsec = ErrorCollection;
            nsec.Add(error);
            ErrorCollection = nsec;
        }
    
        public static List<string> ErrorCollection
        {
            get
            {
                var nsec = HttpContext.Current.Items["ErrorCollection"] as NonStaticErrorCollection ?? new NonStaticErrorCollection();
                return nsec.ItemList;
            }
    
            set
            {
                var nsec = new NonStaticErrorCollection();
                foreach (string error in value)
                {
                    nsec.ItemList.Add(error);
                }
                HttpContext.Current.Items["ErrorCollection"] = nsec;
            }
    
        }
    }
    
    public class NonStaticErrorCollection
    {
        public string[] list()
        {
            return m_sList.ToArray();
        }
    
        public List<string> ItemList
        {
            get
            {
                if (m_sList == null) return new List<string>();
    
                return m_sList;
            }
        }
    
        private readonly List<string> m_sList = new List<string>();
    }
    //Calling Code
    ContextErrorCollection.AddToErrorCollection(string.Format("Adding error number {0} to list...", i));
    Tuesday, June 18, 2013 4:29 PM