2017-07-06 53 views
0

在我的web應用程序中,我需要緩存一些數據,因爲它們是經常需要的 ,但更改頻率較低。爲了保持它們,我製作了一個靜態類,它們將這些字段保存爲靜態值。這些字段在第一次通話時被初始化。請參閱下面的示例。如何防止靜態方法中靜態字段的多重初始化?

public static class gtu 
{ 
    private static string mostsearchpagedata = ""; 
    public static string getmostsearchpagedata() 
    { 
    if (mostsearchpagedata == "") 
    { 
     using (WebClient client = new WebClient()) 
     { 
      mostsearchpagedata = client.DownloadString("https://xxx.yxc"); 
     } 
    } 
    return mostsearchpagedata; 
} 
} 

在這裏webrequest只有一次,它工作正常,但如果他們被快速連續調用時,有大量沒有。的用戶和應用程序池已重新啓動, 根據大多數搜索頁數據被初始化或不初始化,webrequest被多次執行。

如何確保webrequest只發生一次,並且所有其他請求都要等到第一個webrequest完成?

+0

你正在尋找一個單身人士,閱讀有關它。 https://stackoverflow.com/questions/2667024/singleton-pattern-for-c-sharp –

+2

這不是線程安全的,因此導致錯誤。你需要單身這個。參考 - http://csharpindepth.com/Articles/General/Singleton.aspx – Yogi

回答

4

你可以使用System.Lazy<T>

public static class gtu 
{ 
    private static readonly Lazy<string> mostsearchedpagedata = 
     new Lazy<string>(
     () => { 
       using (WebClient client = new WebClient()) 
       { 
        mostsearchpagedata = 
         client.DownloadString("https://xxx.yxc"); 
       } 
      }, 
      // See https://msdn.microsoft.com/library/system.threading.lazythreadsafetymode(v=vs.110).aspx for more info 
      // on the relevance of this. 
      // Hint: since fetching a web page is potentially 
      // expensive you really want to do it only once. 
      LazyThreadSafeMode.ExecutionAndPublication 
     ); 

    // Optional: provide a "wrapper" to hide the fact that Lazy is used. 
    public static string MostSearchedPageData => mostsearchedpagedata.Value; 

} 

總之,拉姆達代碼(您DownloadString本質上)會被調用,當第一個線程調用.Value的懶惰實例。其他線程將執行相同的操作或等待第一個線程完成(有關更多信息,請參閱LazyThreadSafeMode)。值屬性的後續調用將獲取已存儲在Lazy實例中的值。