2012-02-07 20 views
3

我使用Unity 2.0在我的项目中,我读了很多文件在代码Parallel.ForEach块内的同一时间:UNITY:如何使用构造函数注入实现线程安全的Container.Resolve()函数?

Parallel.ForEach(files, currentFile => 
{ 
    using(IMsBuildProjectLoader msBuildProject = Container.Resolve<IMsBuildProjectLoader>(new ParameterOverride("projectFileName", currentFile))) 
    { 
     // file processing 
    } 
} 

解析(新ParameterOverride(“projectFileName”,currentFile)功能有时扔ResolutionFailedException:

ResolutionFailedException: Resolution of the dependency failed, 
type = "Porthus.Build.Common.Interfaces.IMsBuildProjectLoader", name = "(none)". 
Exception occurred while: Calling constructor XXX.Build.Common.Types.MsBuildProjectLoader(System.String projectFileName). 
Exception is: ArgumentException - Item has already been added. Key in dictionary: 'xxx' Key being added: 'xxx' 

这是当同一文件在同一时间下载 - 解决功能与在同一时间同一参数创建两个IMsBuildProjectLoader情况下,它不能被files.Distinct(来解决。 )过滤器。上面的代码只是一个代码示例来解释我的问题

问题是:如何实现线程安全的UnityContainer.Resolve函数?是否可以使用一些Unity扩展类来完成它?

IMsBuildProjectLoader

public interface IMsBuildProjectLoader : IDisposable 
{ 
} 

MsBuildProjectLoader

public class MsBuildProjectLoader : Project, IMsBuildProjectLoader 
{ 
    public MsBuildProjectLoader(string projectFileName) 
     : base() 
    { 
     // Load the contents of the specified project file. 
     Load(projectFileName); 
    } 
} 

MsBuildProjectLoader注册这样:

container.RegisterType<IMsBuildProjectLoader, MsBuildProjectLoader>(); 
+5

这并不直接回答你的问题,但我认为你可能做错了。你的类应该注入一个IMsBuildProjectLoader,并且在你的循环中,你应该调用IMsBuildProjectLoader上的一个方法,该方法将文件名作为参数。然后应该将线程安全性融入到IMsBuildProjectLoader的实现中。我的$ 0.02。 – BFree 2012-02-07 16:33:18

+0

是的,那是另一种选择。谢谢 – Ludwo 2012-02-07 19:54:33

回答

0

解决实际线程安全(或者说在微软P & P的家伙)。 可能不是线程安全的是执行MsBuildProjectLoader,或者更具体地说它是构造函数。 你可能会简单地以相同的异步方式使用

您不包括负载的实施创造MsBuildProjectLoader的新实例,但根据异常蹒跚同样的问题,我会假设它操纵共享或静态字典以非线程安全的方式。 如果出现这种情况,应该使该字典线程安全(例如,将其替换为ConcurrentDictionary)。