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完成?
你正在寻找一个单身人士,阅读有关它。 https://stackoverflow.com/questions/2667024/singleton-pattern-for-c-sharp –
这不是线程安全的,因此导致错误。你需要单身这个。参考 - http://csharpindepth.com/Articles/General/Singleton.aspx – Yogi