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;
}
}
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments