beginner beginner -4 years ago 82
ASP.NET (C#) Question

Is it safe to store and update list in asp.net session via static methods?

Is that code below thread safe? If not could you please suggest the correct approach how to make it thread safe? I just want to avoid Lock if it's redundant

public static IList<string> Urls => urlList;

public static bool AddUrl(string url)
{
var list = urlList;
if (list.Contains(url))
{
return true;
}

list.Add(url);
urlList = list;
return false;
}

private static IList<string> urlList
{
get
{
List<string> list = null;
var sessionValue = HttpContext.Current.Session[sessionKey];
if (sessionValue != null)
{
list = sessionValue as List<string>;
}

if (list == null)
{
list = new List<string>();
}

return list;
}
set
{
HttpContext.Current.Session[sessionKey] = value;
}
}

Answer Source

Thread safety is the least of your concerns. static variables are shared across sessions. You are probably sharing information that should reside in the user context with other users (since you store it in the session rather than the application cache).

For thread safety I would indeed introduce lock. There is another thing that might cause problems when starting a new thread by hand: the HttpContext.Current.Session is not available in that thread since it is specific for the thread the request runs in.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download