2017-03-01 27 views
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; 
    } 
} 

回答

1

線程安全是您最擔心的問題。 static變量在會話中共享。您可能與其他用戶共享應駐留在用戶上下文中的信息(因爲您將其存儲在會話中而不是應用程序緩存中)。

爲了線程安全,我確實會引入鎖。還有另一件事情可能會導致手動啓動一個新線程時出現問題:HttpContext.Current.Session在該線程中不可用,因爲它是針對請求運行的線程。

+0

是否更好地在AddUrl方法中添加鎖,右? – beginner

+0

是的,首先調用'Contains'。如果爲false,則鎖定,再次檢查「Contains」,然後添加,如果仍然爲false。 –