开发者

Acceptable to lock (AppDomain.CurrentDomain)?

开发者 https://www.devze.com 2022-12-21 16:06 出处:网络
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 stateme

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

  1. 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.
  2. 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.
  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消