我有以下财产:
private static Collection<Assembly> _loadedAssemblies = new Collection<Assembly>();
internal static ReadOnlyCollection<Assembly> LoadedAssemblies
{
get { return new ReadOnlyCollection<Assembly>(_loadedAssemblies); }
}
在我循环的另一堂课中LoadedAssemblies
foreach (Assembly assembly in ResourceLoader.LoadedAssemblies)
在遍历程序集时,底层集合 ( _loadedAssemblies
) 有时会发生变化,这会给出一个System.InvalidOperationException
. LoadedAssemblies
确保安全的首选方法是什么?我无法重现该问题,所以我不能只是尝试。
可以吗?
internal static ReadOnlyCollection<Assembly> LoadedAssemblies
{
get { return new ReadOnlyCollection<Assembly>(_loadedAssemblies.ToList()); }
}
编辑
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);
}
}
}