MEF 重组 - 它是否保留现有实例?
假设我有一个像这样的MEF组合:
public class Composition
{
[ImportMany(AllowRecomposition = true)]
IEnumerable<ILongRunningProcess> Processes { get; set; }
public static void Main(string[] args)
{
var composition = new Composition();
using (var catalog = new DirectoryCatalog("."))
{
using (var container = new CompositionContainer(catalog)
{
container.SatisfyImportsOnce(composition);
//Fire off long running processes in response to stimuli
}
}
}
}
根据我见过的文档,我“在使用重组时必须考虑线程安全。”[MSDN]
显然,对于我删除类型的情况,我需要确保我的长时间运行的进程可以安全地进行垃圾收集。但是,对于重组之前存在且重组后仍然存在的类型,每当发生重组时,我是否会为 Processes
的内容获取新实例,或者 MEF 是否能够在目录时保留导入的现有实例是重组的吗?
根据上述文章的建议,对于 ICollection
MEF 将使用 Clear()
和 Add(T)
方法,我不抱希望,但在编写同步代码之前我想确定一下。
编辑我刚刚意识到我不能在静态方法中使用this
;我已经相应地更新了代码:)
Suppose I have a MEF composition like this:
public class Composition
{
[ImportMany(AllowRecomposition = true)]
IEnumerable<ILongRunningProcess> Processes { get; set; }
public static void Main(string[] args)
{
var composition = new Composition();
using (var catalog = new DirectoryCatalog("."))
{
using (var container = new CompositionContainer(catalog)
{
container.SatisfyImportsOnce(composition);
//Fire off long running processes in response to stimuli
}
}
}
}
According to the documentation I've seen, I "have to consider thread-safety when using Recomposition."[MSDN]
Obviously for the case where I removed a type, I need to make sure that my long-running process can be garbage-collected safely. But for types that existed before the recomposition and still exist after the recomposition, will I get new instances back for the contents of Processes
whenever recomposition occurs, or is MEF able to preserve existing instances of imports when a catalog is recomposed?
Based on the above article's suggestion that for ICollection<T>
MEF will use the Clear()
and Add(T)
methods, I'm not hopeful, but I'd like to know for certain before I go write the synchronization code.
EDIT I just realized I can't use this
in a static method; I've updated the code accordingly :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将得到相同的实例,除非带有
ILongRunningProcess
导出的类型将部件创建策略设置为 NonShared。但这并不是真正的线程安全问题。您确实希望确保发生重组时,没有任何内容访问 MEF 容器(其中包括访问 MEF 提供的 Lazy 的 Value 属性之类的内容)。因此,如果长时间运行的进程在不同的线程上运行并且它有自己的导入,则可能会出现线程问题。
You will get the same instances back unless the types with the
ILongRunningProcess
exports on them have the part creation policy set to NonShared.This isn't really a thread-safety issue though. You do want to make sure that when recomposition occurs, nothing is accessing the MEF container (which includes things like accessing the Value property of a Lazy provided by MEF). So if your long running process is running on a different thread and it has its own imports, you can have threading problems.