簡體   English   中英

ASP.NET中作為靜態字段和屬性的全局變量是否不需要鎖定?

[英]Global variables in ASP.NET as static fields and properties no locking required?

這是有關主題global-variables-aspnet的文章

在頁面加載的給定示例中,有一個靜態全局變量的初始化:

protected void Page_Load(object sender, EventArgs e)
{
    // 1.
    // Get the current ImportantData.
    string important1 = Global.ImportantData;

    // 2.
    // If we don't have the data yet, initialize it.
    if (important1 == null)
    {
        // Example code.
        important1 = DateTime.Now.ToString();
        Global.ImportantData = important1;
    }

    // 3.
    // Render the important data.
    Important1.Text = important1;
}

和它的評論:

性能:靜態字段在正常情況下非常有效。 您將只有一份數據副本,並且不需要鎖定。

我的問題是-為什么沒有雙null檢查並且不需要鎖定? 我是否缺少ASP.NET多線程功能?

我認為該文章是錯誤的,至少在考慮以下通用語句時:永遠不需要鎖定。 我不知道有任何機制可以自動序列化對Global類中靜態成員的訪問,並且我也不知道任何可以對Page_Load調用進行序列化的ASP.Net機制。 盡管該文章僅顯示了一次初始化后的讀取訪問權限(在大多數情況下,請參見發布結尾),但有理由認為有人會對此進行誤導,並使用這些靜態成員在不同時間進行讀寫。 例:

public static class Global
{
    public static int PageRequests;
}

...

protected void Page_Load()
{
    // This construct without locking might lead to lost counts
    Global.PageRequests++;
}

這里絕對需要鎖定,除非您不在乎頁面請求計數是否不完全准確。

在特定的情況下,使用DateTime初始化和事后進行只讀訪問,您可以不加鎖地生活。 如果兩個Page_Load線程大約在同一時間成功測試了Important1 == null,則它們都將相同或幾乎相同的DateTime值寫入該變量,並且從稍后開始,此變量將不再更改,因為Important1 = = null則求值為false。 但這是一個非常特殊的情況,沒有關系。 當然不是概括。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM