File locks or when garbage collection goes bad

With introduction of garbage collection (System.GC name space) in .Net, life of the Windows programmer become easy – no need to worry about releasing objects, code become simpler, etc.
In “old” time one would need to use Interfaces to achieve similar functionality and it does have some advantage even over GC – immediate garbage collection or release of allocated resources/objects.

When writing code in .Net some of us take many things for granted and not always keep in mind that many operations are performed in the context of the unmanaged code or in the “old way”…

File operations or legacy code wrappers are perfect example.
Just because library is available as managed code, it does not mean that everything has ability to “self-heal”.
For example in code file is open for edit with lock being placed.
If the file in not closed explicitly, it would be a responsibility of the owner process to release the lock at the time of releasing associated resources – when process is destroyed.

With garbage collection, just because we are no longer using/owning the process/object, it does not mean that it has been destroyed immediately after. GC management core will release object when it “feels” fit, therefore introducing latency into the process.

Off course, proper way would be to be more careful within the code and make sure any locks are released in managed and predictable way: Open/Close, Lock/Unlock, … Easy solution, but not always accessible, especially when working with 3rd party libraries.

So instead, we can force GC manager to “collect garbage” in-place with the following small code:

// See code follow up below
System.GC.Collect();
System.GC.WaitForPendingFinalizers();

What does it do?
First call will instruct GC manager to start the process (1), while second (2) will make sure that we wait for process to be completed.

In the case of the file locks, only after GC has released process which placed the lock in the first place, we can manipulate with the file (ex. delete, rename, move).

This entry was posted in Fun stuff with C#, Technology and tagged , , , , , . Bookmark the permalink.

Leave a Reply