I have the following property:
private static Collection<Assembly> _loadedAssemblies = new Collection<Assembly>();
internal static ReadOnlyCollection<Assembly> LoadedAssemblies
{
get { return new ReadOnlyCollection<Assembly>(_loadedAssemblies); }
}
In another class I loop through LoadedAssemblies
foreach (Assembly assembly in ResourceLoader.LoadedAssemblies)
While looping through the assemblies the underlying collection (_loadedAssemblies
) changes sometimes which gives a System.InvalidOperationException
. What is the preferred way to make LoadedAssemblies
safe? I cannot reproduce the problem so I can't just try it.
Is it okay to do?
internal static ReadOnlyCollection<Assembly> LoadedAssemblies
{
get { return new ReadOnlyCollection<Assembly>(_loadedAssemblies.ToList()); }
}
Edit
public static void Initialize()
{
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
AddAssembly(assembly);
}
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyLoad += OnAssemblyLoad;
}
private static void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
AddAssembly(args.LoadedAssembly);
}
private static void AddAssembly(Assembly assembly)
{
AssemblyName assemblyName = new AssemblyName(assembly.FullName);
string moduleName = assemblyName.Name;
if (!_doesNotEndWith.Exists(x => moduleName.EndsWith(x, StringComparison.OrdinalIgnoreCase)) &&
_startsWith.Exists(x => moduleName.StartsWith(x, StringComparison.OrdinalIgnoreCase)))
{
if (!_loadedAssemblies.Contains(assembly))
{
_loadedAssemblies.Add(assembly);
}
}
}