gpt4 book ai didi

c# - MEF 组合问题,多线程

转载 作者:太空狗 更新时间:2023-10-29 19:53:44 26 4
gpt4 key购买 nike

我有以下代码:

public class Temp<T, TMetadata>
{
[ImportMany]
private IEnumerable<Lazy<T, TMetadata>> plugins;

public Temp(string path)
{
AggregateCatalog aggregateCatalog = new AggregateCatalog();
aggregateCatalog.Catalogs.Add(new DirectoryCatalog(path));
CompositionContainer container = new CompositionContainer(aggregateCatalog);
container.ComposeParts(this);
}

public T GetPlugin(Predicate<TMetadata> predicate)
{
Lazy<T, TMetadata> pluginInfo;

try
{
pluginInfo = plugins.SingleOrDefault(p => predicate(p.Metadata));
}
catch
{
// throw some exception
}

if (pluginInfo == null)
{
// throw some exception
}

return Clone(pluginInfo.Value); // -> this produces errors
}
}

我有一个 Temp 对象,我从多个线程调用 GetPlugin()。有时我会遇到奇怪的构图错误,但我找不到重现的方法。例如:

"System.InvalidOperationException: Stack empty.
at System.Collections.Generic.Stack`1.Pop()
at System.ComponentModel.Composition.Hosting.ImportEngine.TrySatisfyImports(PartManager partManager, ComposablePart part, Boolean shouldTrackImports)
at System.ComponentModel.Composition.Hosting.ImportEngine.SatisfyImports(ComposablePart part)
at System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition)
at System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart)
at System.ComponentModel.Composition.ExportServices.GetCastedExportedValue[T](Export export)
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at Temp`2.GetPlugin(Predicate`1 predicate)..."

可能是什么原因以及如何修复此代码?

最佳答案

CompositionContainer 类有一个 little-known constructor它接受一个 isThreadSafe 参数(出于性能原因默认为 false)。如果您将创建容器并将此值设置为 true,我相信您的问题将得到解决:

CompositionContainer container = new CompositionContainer(aggregateCatalog, true);

附带说明,与原始问题无关,您可以使用 an export factory 而不是在插件上调用 Clone()相反 - 这样您就不必实现自己的克隆方法,因为 MEF 将为您创建一个新实例。

关于c# - MEF 组合问题,多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21155710/

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