c# - ReadOnlyCollection property underlying Collection is modified while iterating -
i have following property:
private static collection<assembly> _loadedassemblies = new collection<assembly>(); internal static readonlycollection<assembly> loadedassemblies { { return new readonlycollection<assembly>(_loadedassemblies); } }
in class loop through loadedassemblies
foreach (assembly assembly in resourceloader.loadedassemblies)
while looping through assemblies underlying collection (_loadedassemblies
) changes gives system.invalidoperationexception
. preferred way make loadedassemblies
safe? cannot reproduce problem can't try it.
is okay do?
internal static readonlycollection<assembly> loadedassemblies { { 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); } } }
the suggestion have in question work. is:
internal static readonlycollection<assembly> loadedassemblies { { return new readonlycollection<assembly>(_loadedassemblies.tolist()); } }
the reason problems come _loadedassemblies
being changed while enumerating on it. of course happens because readonlycollection
wrapper around _loadedassemblies
uses enumerator of base collection.
if _loadedassemblies.tolist()
create new list copy of original _loadedassemblies
. have same elements @ time of creation never updated again (since don't have reference new collection unable modify it). means when _loadedassemblies
updated new list inside readonlycollection
blissfully unaware of change , enumeration continue without problem end.
Comments
Post a Comment