1

I am writing a web app for SharePoint 2013 and am running into some interesting behavior. Basically, I am making a series of web requests, but first need to store those in a Dictionary for use later. However, if I open 3 tabs while debugging and hit them at the same time, I see the Dictionary object is not emptied and causes an exception when it tries to add the same endpoint multiple times. Here is the relevant code of the app:

public partial class TestControl : UserControl
{
    protected static Dictionary<string, string> _endpoints = new Dictionary<string, string>();

    protected void Page_Load(object sender, EventArgs e)
    {
        //clear the lists of endpoints each time the page is loaded
        _endpoints.Clear();
        ...
        MethodThatAddsToDictionary();
       ...
    }

    public static void MethodThatAddsToDictionary()
    {
        ...
        _endpoints.Add(response.First(), response.Last());
    }
}

Debugging, sometimes MethodThatAddsToDictionary() is called twice before the _endpoints.Clear() is run at the top under the Page_Load event and I'll get an ArgumentException saying:

an item with the same key has already been added

I feel like I'm missing something basic about the lifecycle of the app but haven't found anything that works so far. I could wrap the .Add() in a conditional to check for the key before I add it, but I feel like that is a bandaid. What am I missing?

Thanks in advance!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.