0
線程安全以下的代碼?如果不是,你可以請建議正確的方法如何使它線程安全?我只是想避免鎖定,如果它是多餘的通過靜態方法在asp.net會話中存儲和更新列表是否安全?
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;
}
}
是否更好地在AddUrl方法中添加鎖,右? – beginner
是的,首先調用'Contains'。如果爲false,則鎖定,再次檢查「Contains」,然後添加,如果仍然爲false。 –