2012-01-17 3 views
0

ASP.NET 웹 응용 프로그램에서 사이트의 모든 사용자가 액세스 할 수 있지만 기록 된 사용자에 의해 수정 가능한 단일 상태를 유지하는 데이터 배열을 저장하려고합니다. 이것에 대한 최선의 접근 방법은 무엇입니까? 아마도 응용 프로그램 전체 변수를 사용하는 경로를 찾을 수는 있지만 더 나은 대안이 있습니까? 또한 단순히 데이터베이스에 상태를 저장하고 각 요청을 검색하는 방법을 고려했습니다. 상태가 지속 될 필요가없는 경우 이안사용자간에 세션 또는 응용 프로그램 데이터 공유 - 모범 사례

+0

내가 그런 퀘스트 XML 파일을 사용합니다. – Bastardo

답변

2

갈 수있는 가장 좋은 방법은 System.Web.HttpContext.Current.Cache 경유 미리

감사합니다.

캐시는 페이지의 컨텍스트에서 사용할 수도 있습니다.

+0

감사합니다. 그것을 줄 것이고, 그것이 나를 위해 어떻게 돌아가는지 알 것이다. – Ian

+0

콘텐츠를 특정 사용자의 세션에 맞게 캐시하지 않습니까? – Ian

+0

캐시는 응용 프로그램 와이드이며 세션은 사용자별로 다릅니다. –

1

내 경험으로는 System.Web.HttpContext.Current.Cache과 캐시 파일을 사용합니다. OS의 메모리가 부족하면 IIS가 모든 캐시를 지 웁니다. 모든 사용자의 상태를 유지하려면 파일의 상태 사본을 보관해야합니다 (파일의 객체 직렬화).

예 : 많은 사용자가 캐시에 대기열 목록을 보관하고 싶습니다. IIS가 캐시 개체를 재설정하면 캐시 파일에서 읽을 수 있습니다.

  Stack<string> list = null; 
      List<string> returnlist = new List<string>(); 

      try 
      { 
       if (System.Web.HttpContext.Current.Cache["PushQueueList"] != null) 
       { 
        try 
        { 
         list = (Stack<string>)System.Web.HttpContext.Current.Cache["PushQueueList"]; 
        } 
        catch (Exception ex) 
        { 
         list = null; 
         //Log.LogToFile("PushQueueListError1:" + ex.Message); 
        } 
       } 
       if (list == null)//memory cache is null ,then read cache file 
       { 

        try 
        { 
         list = (Stack<string>)Serialize.DeSerializeObj("pushqueue");//Deserialize object from file 
        } 
        catch (Exception ex) 
        { 
         list = null; 
         //Log.LogToFile("PushQueueListError2:" + ex.Message); 
        } 
       } 
       if (list == null || list.Count == 0) 
       { 
        if (list!=null && list.Count == 0) 
        { 
         return new List<string>(); 
        } 
        try 
        { 
         System.Web.HttpContext.Current.Cache.Remove("PushQueueList"); 
        } 
        catch (Exception) 
        { 
        } 
        //Log.LogToFile("PushQueueList is empty,reload it"); 
        DataSet ds = DB.GetSendQueueUserIDList(); ; 
        if (ds != null) 
        { 
         list = new Stack<string>(); 
         DataView dv = ds.Tables[0].DefaultView; 
         for (int i = 0; i < dv.Count; i++) 
         { 
          list.Push(dv[i].Row["UserID"].ToString()); 
         } 
         dv.Dispose(); 
         ds.Dispose(); 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       //Log.LogToFile("PushQueueListError:" + ex.Message); 
      } 

      if (list != null && list.Count > 0) 
      { 
       for (int i = 0; i < ReturnCount; i++) 
       { 
        if (list.Count > 0) 
        { 
         returnlist.Add(list.Pop()); 
        } 
        else 
        { 
         Log.LogToFile("PushQueueList OK"); 
         break; 
        } 
       } 
       System.Web.HttpContext.Current.Cache.Add("PushQueueList", list, null, DateTime.Now.AddDays(1), 
                  TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, 
                  null); 
       Serialize.SerializeObj(list, "pushqueue"); 
      } 
      return returnlist; 
     } 

일련 방법

은 다음과 같습니다 :

public static bool SerializeObj(object obj, string FileName) 
    { 
     string LogFileDir = System.Configuration.ConfigurationManager.AppSettings["LogFile"]; 
     if (!System.IO.Directory.Exists(LogFileDir)) 
     { 
      System.IO.Directory.CreateDirectory(LogFileDir); 
     } 
     string FilePath = LogFileDir + FileName + "_" + DateTime.Now.ToString("yyyyMMdd") + ".bin"; 
     try 
     { 
      IFormatter _formatter = new BinaryFormatter(); 
      using(Stream _stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None)) 
      { 
       _formatter.Serialize(_stream, obj); 
       _stream.Close(); 
      } 
      return true; 
     } 
     catch (Exception ex) 
     { 
      return false; 
     } 
    } 

    public static object DeSerializeObj(string FileName) 
    { 
     try 
     { 
      string LogFileDir = System.Configuration.ConfigurationManager.AppSettings["LogFile"]; 
      if (!System.IO.Directory.Exists(LogFileDir)) 
      { 
       System.IO.Directory.CreateDirectory(LogFileDir); 
      } 
      object objStd = null; 
      string FilePath = LogFileDir + FileName + "_" + DateTime.Now.ToString("yyyyMMdd") + ".bin"; 

      using(Stream _stream = File.Open(FilePath, FileMode.Open)) 
      { 
       BinaryFormatter _b = new BinaryFormatter(); 
       objStd = _b.Deserialize(_stream); 
       _stream.Close(); 
      } 
      return objStd; 
     } 
     catch (Exception ex) 
     { 
      return null; 
     } 
    } 
관련 문제