I asked this over in the SharePoint Stack Exchange but figured it might not be a SharePoint-specific question and might have more to do with the .NET page lifecycle. The original question can be found here.
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!