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)使用反射。
所以我的問題是:
- 有實現使用公共/ protected成員清理功能的方法嗎? WeakEventManager.Purge可能很有用,但我不知道如何使用它。
- 是否有一種簡單的方法在基於Windows.Forms的應用程序中運行WPF消息循環?
+1對於一個有趣的答案,雖然性能不是我主要關心的地方。我非常感謝一個不依賴無證私人函數的解決方案。 – Henrik 2011-02-24 15:48:25