2017-07-06 48 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实例中的值。