I want to enumerate all loaded assemblies in an Asp.NET application, using AppDomain.CurrentDomain.GetAssemblies()
. However, when checking the documentation for AppDomain, I find the following statement:
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Since GetA开发者_JS百科ssemblies()
is an instance method, I take this as I have to make take some kind of lock around that call, if not for anything else so to prevent anyone else from loading a new assembly into the domain while I'm enumerating the current ones. I would expect AppDomain to provide some kind of SyncRoot property, but it doesn't, and I have not found any information on the web about how to do.
How am I supposed to synchronize this call?
Edit
- I know that the lock statement is used to create a cooperative lock, this is exactly the reason that I want to lock the AppDomain in the same way everyone else does (or should do), rather than create my own lock that won't prevent code that's not mine from loading assemblies while I'm enumerating them.
- I know that locks that can be taken by anyone are usually a bad idea, but I also know that not taking a lock when performing unsafe operations is even worse.
- Both answers so far say that GetAssemblies() is, in fact, thread-safe. This makes sense to me, and I would really expect it to be the case, but how do you know it? Does anyone have a reference to support this claim? My google-fu has failed me and Reflector shows that this method is a thin wrapper around an internal native method.
SyncRoot properties in general are a very bad idea. One reason why is it's possible for 2 independently developed libraries to unknowingly decide to lock against a shared SyncRoot property and quickly introduce deadlocks into the application. Locking is an operation that cannot easily be reliably shared between two independent components. The best strategy here is to develop your own lock which is used by your components to synchronize access.
In this case though calling GetAssemblies is safe to do from multiple threads so no locking is needed. The warning you see is a general statement added to every class in the BCL unless the author specifically designed the type for thread safety and removed the message.
That is a standard disclaimer; you don't need to worry about it.
In general, as long as you (or another thread) do not modify the object, instance methods can be called from multiple threads.
Note that you should never lock on an AppDomain object.
精彩评论