gpt4 book ai didi

c# - MEF 和对象处理

转载 作者:行者123 更新时间:2023-11-30 15:30:04 24 4
gpt4 key购买 nike

当我创建一个对象并将它添加到容器中,然后我就完成了它,我如何才能确保它被正确处理?

阅读 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 和对象处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com