2010-12-14 61 views
0

我相信這是一個WCF問題,但也許它也與Azure有關。我有一個執行一些鐵python腳本的WCF項目。我想保留已編譯腳本的緩存,所以他們不需要每次重新編譯。在Azure WCF項目中創建全局對象

當這些腳本第一次運行時,它們有時可能需要2或3秒。但是,下一次運行時,它們將在幾毫秒內執行。我想緩存腳本源,以便只編譯一次,然後重複用於使用我的服務的任何人。目前,每當有人連接到我的服務時,我的整個服務行爲都會被實例化。有沒有辦法讓我的ScriptCache對象在應用程序的整個生命週期內持久存在?

下面是我正在玩的一些示例代碼。

[ServiceBehavior] 
public class Foo: IFoo { 
    ScriptEngine engine = Python.CreateEngine(); 
    Dictionary<string, ScriptHost> ScriptCache = new Dictionary<string, ScriptHost>(); 
    public fooBar doSomething() { 
     ... 
     for (int editIndex = 0; editIndex < Edits.Count; editIndex++) { 
      ScriptHost mCurrentScript; 
      if (!ScriptCache.TryGetValue(Edits[editIndex], out mCurrentScript)) { 
       mCurrentScript = new ScriptHost(LoadScriptFromStorage(Edits[editIndex]), Edits[editIndex], engine); 
       ScriptCache.Add(Edits[editIndex], mCurrentScript); 
      } 
      mEditTimer.Start(); 
      mCurrentScript.runScript(mCurrentObj); 
      mEditTimer.Stop(); 
      WriteToLog(mJobID, "Edit: {0}\tTime: {1}", Edits[editIndex], mEditTimer.Elapsed.TotalMilliseconds); 
      mEditTimer.Reset(); 
      mEditTimer.Start(); 
      mCurrentScript.runScript(mCurrentObj); 
      mEditTimer.Stop(); 
      WriteToLog(mJobID, "Edit: {0}\tTime: {1}\t2nd run", Edits[editIndex], mEditTimer.Elapsed.TotalMilliseconds); 
      mEditTimer.Reset(); 
      } 
    } 

回答

1

最簡單的解決方案是簡單地將屬性標記爲靜態。我猜測可能這個代碼可能是並行調用的,所以你需要確保添加到字典中是線程安全的。我在下面包含了一個代碼片段。我會替換ScriptCache.Add的呼叫,並撥打AddToCache以下的功能

[ServiceBehavior] 
public class Foo : IFoo 
{ 
    static ScriptEngine engine = Python.CreateEngine(); 
    static Dictionary<string, ScriptHost> ScriptCache = new Dictionary<string, ScriptHost>(); 
    static object _dictionaryLock = new object(); 

    static void AddToCache(string edit, ScriptHost host) 
    { 
     lock (_dictionaryLock) 
     { 
      if (!ScriptCache.ContainsKey(edit)) 
      { 
       ScriptCache.Add(edit, host); 
      } 
     } 
    } 

    ... 
} 
+0

謝謝!這工作完美。它表現得好像整個班級在每次打電話時都被實例化。我想(如果是這種情況),即使靜態對象將被重新創建。 +1 ...感謝您的幫助! – Brosto 2010-12-14 21:22:31