Tuesday, September 29, 2009

Automating Excel from C# Pt. 1

Recently, I have wanted to convert Excel spreadsheets to CSV files for further processing. Excel provides a COM Automation model for using its functionality from 3rd party applications.

One of the things about COM Automation is that if you don't close all of the handles you are using in the application being automated, orphaned instances can be left running and they will never quit unless you use Task Manager to kill them or reboot the computer.

So, the automating application needs to be very careful to get rid of everything it is referencing in the automated process to allow it to shut down. The problem is, .NET is a garbage-collected environment, and this means that objects are destroyed, or released, whenever the framework decides that memory should be freed up. Unlike C++ destructors, which are always called immediately when a variable goes out of scope or is delete'd, .NET finalizers are called only when the framework wants to free memory. Exactly when that happens cannot be known with certainty. Oh, objects will be released eventually, but not necessarily when the application might like.

Therefore, the .NET framework provides the IDisposable interface, which allows the non-.NET allocated portions of an object to be immediately freed without the .NET portion being freed. This is what we need to use when automating COM so that COM handles are released in a controlled, dependable, and timely fashion.

In the next part to this series, I will talk about the IDisposable interface.

No comments:

Post a Comment