2009-08-19 28 views
2

在Windows.Forms應用程序中使用這裏所述http://wekempf.spaces.live.com/blog/cns!D18C3EC06EA971CF!373.entry的弱事件時,WeakEventManager會泄漏WeakReference對象。 我認爲這是因爲沒有WPF消息循環,CleanupOperation從不執行,雖然ScheduleCleanup在WeakEventManager.ProtectedAddListener中調用。在Windows.Forms中使用WeakEventManager應用程序

作爲一種變通方法我實現了一個清理功能,像這樣:

internal bool Cleanup() 
{ 
    // The following is equivalent to 
    // return this.Table.Purge(false); 
    // but we need to use reflection to access the private members. 

    PropertyInfo pi = typeof(WeakEventManager).GetProperty("Table", BindingFlags.Instance | BindingFlags.NonPublic); 
    if (pi == null) 
     return false; 
    object table = pi.GetValue(this, null); 
    MethodInfo mi = table.GetType().GetMethod("Purge", BindingFlags.Instance | BindingFlags.NonPublic); 
    if (mi == null) 
     return false; 
    return (bool)mi.Invoke(table, new object[] { false }); 
} 

和以後每隔例如調用此第16次致電ProtectedAddListener

這有效,但顯然我喜歡避免這種(ab)使用反射。

所以我的問題是:

  1. 有實現使用公共/ protected成員清理功能的方法嗎? WeakEventManager.Purge可能很有用,但我不知道如何使用它。
  2. 是否有一種簡單的方法在基於Windows.Forms的應用程序中運行WPF消息循環?

回答

2

此代碼構建了一個可以保持緩存的靜態函數。它會消除每次運行時的反射痛苦,並且基本上就是你所擁有的。每次將它緩存在某處並通過傳遞您的弱事件管理器來調用它。除了一次打擊(在建築/編譯期間),沒有進一步的反思。

using System.Windows; 
    using System.Linq.Expressions; 
    using Expression = System.Linq.Expressions.Expression; 

    static void Main(string[] args) 
    { 
     Func<WeakEventManager, bool> cleanUpFunction = BuildCleanUpFunction(); 
    } 

    private static Func<WeakEventManager, bool> BuildCleanUpFunction() 
    { 
     ParameterExpression managerParameter = Expression.Parameter(
      typeof(WeakEventManager), 
      "manager" 
     ); 
     return Expression.Lambda<Func<WeakEventManager, bool>>(
      Expression.Call(
       Expression.Property(
        managerParameter, 
        "Table" 
       ), 
       "Purge", 
       Type.EmptyTypes, 
       Expression.Default(
        typeof(bool) 
       ) 
      ), 
      managerParameter 
     ).Compile(); 
    } 
+0

+1對於一個有趣的答案,雖然性能不是我主要關心的地方。我非常感謝一個不依賴無證私人函數的解決方案。 – Henrik 2011-02-24 15:48:25

相關問題