This project has moved. For the latest updates, please go here.

ReaderWriterLock Deadlock?

Sep 5, 2014 at 12:14 PM
Hi there,

I use the reader writer lock for the following scenario. We have some plugins in separate app-domains. They will be reloaded by a file watcher and registered to a registry. To resolve issues with plugins they are used at the moment I use a readerwriterlock for synchronizatoon. Below is my code.
public sealed class Registry<TRegistration> : DisposableMarshalByRefObject, IRegistry<TRegistration> where TRegistration : RegistrationBase
    {
        private readonly AsyncReaderWriterLock lockObject = new AsyncReaderWriterLock();
        private readonly Dictionary<string, TRegistration> registrations = new Dictionary<string, TRegistration>();

        public void Register(TRegistration registration)
        {
            Guard.NotNull(registration, "registration");

            using (lockObject.WriterLock())
            {
                registrations[registration.Provider.CompanyShortKey] = registration;
            }
        }

        public void Unregister(string companyShortKey)
        {
            Guard.NotNullOrEmpty(companyShortKey, "companyShortKey");

            using (lockObject.WriterLock())
            {
                registrations.Remove(companyShortKey);
            }
        }

        public async Task UseProvidersAsync(Func<IReadOnlyDictionary<string, TRegistration>, Task> action)
        {
            Guard.NotNull(action, "action");

            using (await lockObject.ReaderLockAsync())
            {
                await action(registrations);
            }
        }
    }
In some rare situations I get a deadlock I think. There is no update and the plugins are not used anymore. It is really hard to reproduce at the moment. Can you see a potential issue?
Coordinator
Sep 5, 2014 at 1:08 PM
I strongly discourage calling arbitrary code while holding a lock; that's usually a recipe for deadlock. In this case, if the action passed to UseProvidersAsync tries to register or unregister a plugin, then yes, this code would deadlock.

That's the only thing I can see right off. But I'm not the best at cross-AppDomain scenarios, so there could be something there I'm missing.

-Steve
Sep 5, 2014 at 1:12 PM
Yes, you are right. I think I dont need the lock at all here. In case the app-domain is unloaded while a operation is still running I get an exception which is very easy to catch. I should not get any problems here.