首页 / C# / c#-MEF和对象处置
c#-MEF和对象处置
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#-MEF和对象处置,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2578字,纯文字阅读大概需要4分钟。
内容图文
![c#-MEF和对象处置](/upload/InfoBanner/zyjiaocheng/679/dff611d6f3c64459be101abc4b84802b.jpg)
当我创建一个对象并将其添加到容器中,然后完成操作后,如何确保正确处理该对象?
读http://msdn.microsoft.com/en-us/library/ee155691(v=vs.110).aspx说
For long-lived composition containers, memory consumption by parts
with a creation policy of non-shared can become a problem. These
non-shared parts can be created multiple times and will not be
disposed until the container itself is disposed. To deal with this,
the container provides the ReleaseExport method. Calling this method
on a non-shared export removes that export from the composition
container and disposes it. Parts that are used only by the removed
export, and so on down the tree, are also removed and disposed. In
this way, resources can be reclaimed without disposing the composition
container itself.
因此,例如,如果我在MEF中使用Caliburn.micro之类的东西并创建一个新的ViewModel,则当ViewModel关闭时,如果我在容器上添加ReleaseExport调用,此操作是否会清理引用,使其不再占用内存? (这是正确的方法吗?)
另外,调用ReleaseExport会阻止我将来创建该类型的另一个对象,还是目录仍然包含该项目,并且我可以随时重新创建它?
解决方法:
MEF允许两种类型的导出-共享和非共享.
共享出口就像单身人士-每个消费者共享同一实例.这些共享实例由MEF直接管理.当您在MEF容器上调用Dispose()时,它将自动按照相反的导入顺序释放这些对象.
非共享资源更加复杂.由于存在多个实例,因此MEF无法保证发布的正确顺序.在这种情况下,您应遵循与调用Dispose()时所使用的指导相同的指导,以确定何时释放导入的对象.
每个非共享的MEF导入对象都应拥有一个负责其生命周期的所有者-通常是首先导入该对象的父对象.一旦父对象确保没有人使用此导入的对象,它将在其上调用ReleaseExport.典型的模式是在所有者对象的Dispose()中释放导入的对象.
class OwnerClass : IDisposable
{
[Import(RequiredCreationPolicy=CreationPolicy.NonShared)]
private ConsumedClass myInstance;
[Import(RequiredCreationPolicy=CreationPolicy.Shared)]
private CompositionContainer container;
// Do stuff
public void Dispose()
{
container.ReleaseExport(myInstance);
{
}
调用ReleaseExport会从容器中释放该特定实例.定义保留在目录中.因此,您仍然应该能够创建更多实例.这是一个很好的讨论:
https://mef.codeplex.com/discussions/228535
The job of ReleaseExport is to cleanup a particular export and it’s
dependencies from the container early, meaning before disposing of the
container itself which will cleanup and dispose all objects
constructed by the container. Now calling ReleaseExport will do
different things depending on the particular export, for example for a
Shared export it will actually do nothing but for a NonShared export
it will release it and walk its dependency graph releasing them but
again it will stop and do nothing for any dependencies that are Shared
exports.
内容总结
以上是互联网集市为您收集整理的c#-MEF和对象处置全部内容,希望文章能够帮你解决c#-MEF和对象处置所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。