Search code examples
c#iteratorregistry

Is yield-return pattern safe to use on Registry keys


In my company, I have seen some code that searches Windows Registry for some keys and returns an IEnumerable where T is an object that holds the values and the data of the registry keys that match the find pattern. The method that does this processing uses yield-return pattern. The registry key is closed after the foreach that contains the yield-return completes.

My question is whether it is a safe way to access the Windows registry? Since the key is not closed until the iteration is complete, what would be the impact if, say there is a power failure/system crash, considering that there might be arbitrary delays before the iteration completes?

I might also mention that at any point of time, the number of elements returned would only be a handful - say 20 at maximum.


Solution

  • Keeping the Registry keys open for reading, will mainly tie up OS resources... Hence

    1. If there is a power failure, or a system crash - I don't think you have anything to worry about this code.. OS itself is gone, and all the resources like handles, held by any process are all gone (There is no smart persistence from OS at work here).

    2. On the flip side, it is always considered a good practice to release any OS resource as soon as possible... If the list is small, I'd just read it at once, and return the values from an in memory list.. Because depending on what code is using this API, and how, in theory it is open to abuse by its callers..

    I'd say, on your part its a good call and due diligence at least contemplating the implications of keeping system resources tied up longer than necessary.

    As peter mentioned in the comment, do wrap any disposable objects in a using statement.