我有增加内存的问题。我在 caliburn.micro 中使用 MEF 创建新屏幕 - WPF 窗口。
屏幕/视图的视图模型如下所示:
[Export(typeof(IChatViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ChatViewModel : Screen, IChatViewModel
{}
在创建时我使用 ExportFactory,控制器在这里:
public interface IViewModelsControler
{
ExportLifetimeContext<IChatViewModel> CreatChatViewModel();
}
[Export(typeof(IViewModelsControler))]
public class ViewModelsControler : IViewModelsControler
{
[Import]
public ExportFactory<IChatViewModel> ChatViewFactory { get; set; }
public ExportLifetimeContext<IChatViewModel> CreatChatViewModel()
{
return ChatViewFactory.CreateExport();
}
}
我在 ChatScreenManager 类中使用 ViewModelsControler 类。此类打开/删除聊天屏幕。
就这个:
[Export(typeof(IChatScreenManager))]
public class ChatScreenManager : IChatScreenManager
{
private IWindowManager _windowManager;
[Import]
public IViewModelsControler ViewModelControler { get; set; }
[ImportingConstructor]
public ChatScreenManager(IWindowManager windowManager)
{
_windowManager = windowManager;
ActiveChatScreens = new Dictionary<string, ExportLifetimeContext<IChatViewModel>>();
}
//store active screen
public Dictionary<string, ExportLifetimeContext<IChatViewModel>> ActiveChatScreens { get; set; }
public void OpenChatScreen(DetailData oponent, string avatarNick, BitmapImage avatarImage)
{
if (!ActiveChatScreens.ContainsKey(oponent.Info.Nick))
{
//create new chat screen with view model controler
ExportLifetimeContext<IChatViewModel> chatScreen = ViewModelControler.CreatChatViewModel();
//show
_windowManager.Show(chatScreen.Value);
//add ref to the dic
ActiveChatScreens.Add(oponent.Info.Nick, chatScreen);
}
}
public void RemoveChatScreen(string clossingScreen)
{
MessageBox.Show(GC.GetTotalMemory(true).ToString());
ActiveChatScreens[clossingScreen].Dispose();
ActiveChatScreens.Remove(clossingScreen);
GC.Collect();
GC.SuppressFinalize(this);
MessageBox.Show(GC.GetTotalMemory(true).ToString());
}
}
我的问题是:
- 我从 ChatScreenManager 调用 OpneChatScreen 方法打开新的 WPF 窗口
- 将此窗口上的引用添加到字典。
- 当我关闭窗口时,我调用 RemoveChatScreen。
在 RemoveChaScreen 中:
- 我得到总内存,例如是 37,000K
- 然后我在 ExportLifetimeContext chatScreen 上调用 Dipose 方法
- 强制GC
- 并获取总内存,例如是 39,000K
内存使用量仍在增加。我希望如果我在对象 ChatViewModel 和 ChatView 对象上调用 Dispose 方法,这些对象都会被销毁。