[英]Best Practice CleanUp ViewModelLocator
ViewModel in my MVVM Light application has some resourse, that must be dispose when application is closing. 我的MVVM Light应用程序中的ViewModel有一些资源,必须在应用程序关闭时进行处置。 I have CleanUp method in ViewModelLocator to do it. 我在ViewModelLocator中具有CleanUp方法来执行此操作。 Where is right place in my application to call CleanUp method. 在我的应用程序中正确的地方调用CleanUp方法。
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
}
public MainViewModel Main
{
get
{
return SimpleIoc.Default.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
var main=SimpleIoc.Default.GetInstance<MainViewModel>();
main.Dispose();
}
}
public class MainViewModel:ViewModelBase, IDisposable
{
public void Dispose()
{
disposableResoure.Dispose();
}
}
You could use the Closing
or Closed
event on the MainWindow
class of the Application
class - probably best use the Closed
event because the window will no longer be visible. 您可以在Application
类的MainWindow
类上使用Closing
或Closed
事件-可能最好使用Closed
事件,因为该窗口将不再可见。
http://msdn.microsoft.com/en-us/library/system.windows.application.mainwindow(v=vs.110).aspx http://msdn.microsoft.com/zh-cn/library/system.windows.application.mainwindow(v=vs.110).aspx
Or you could use the Exit
event on the Application
class. 或者,您可以在Application
类上使用Exit
事件。
http://msdn.microsoft.com/en-us/library/system.windows.application.exit(v=vs.110).aspx http://msdn.microsoft.com/zh-CN/library/system.windows.application.exit(v=vs.110).aspx
If you're exiting the application, then why clean up resources at all? 如果要退出该应用程序,那么为什么要清理所有资源? The OS will do that when the process is torn down. 当进程被拆除时,操作系统将执行此操作。 You want to call Dispose()
on an IDisposable
when you no longer need the resource so you can clean up all the unmanaged resources. 当您不再需要资源时,您想在IDisposable
上调用Dispose()
,以便可以清理所有非托管资源。 If the process is getting tossed out, then there isn't a need to call it since garbage collection isn't going to happen in the memory space after the process is gone. 如果该过程被抛弃,则无需调用它,因为在该过程结束后,不会在内存空间中进行垃圾回收。
I agree that Disposing of resources after your Window has gone out of "scope" to the user and is no longer needed, but the end of the process is not necessary. 我同意,在您的Window已超出用户的“范围”之后,不再需要处理资源,但是过程的最后不必这样做。
Here is another way to use the Cleanup()
method: 这是使用Cleanup()
方法的另一种方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.