The Excel object we access is a COM object. For COM objects (including interfaces), each reference to an object (in C ++, this operation corresponds to ComCreateObject and QueryInterface) will increase the reference count of this object, releasing an object reference reduces the reference count (corresponding to Release in C ++ ). In C ++, object and interface creation and reference are explicit (code needs to be written), so we know exactly which objects and interfaces should be released after use, the release operation is also explicit. But in C #, creation and reference are implicit, but release needs to be explicit, that is, we need to add the code for manual release. When we use code prompts to write a C # program, we may not realize that the statement is actually creating or referencing a COM object or interface. Therefore, there is no explicit release operation. As a result, Excel remains in the memory until there are unreleased references ..... The End of the World or we can manually kill it.
Every time you call the previous code to create an Excel Application, an Excel. Exe file is displayed in the Task Manager List. All the accumulated results are expected.
You can release an object reference in the following ways:
using System.Runtime.InteropServices;.......Marshal.ReleaseComObject(obj);
Because this operation is used multiple times, you need to write a method:
protected void releaseComObject(object obj){ try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); } finally { }}
N objects in Excel increase the reference count. Therefore, you need to be careful with this. Generally, objects with members and objects with s that can be accessed in arrays generate references, such as Excel. range. the Font object, Sheets object, and Cells object must be explicitly released. But this will also lead to a new problem: too frequent reference objects and release references, leading to performance degradation. If we release them together, the memory consumption will be huge. This situation needs to be treated differently according to the actual situation.
In addition, because each time an Excel. Application is created and finally destroyed, it will take about 10 seconds (on my machine) to start Excel ).
You can also write a Singlton to create a unique Excel. Application instance and complete data operations. This will have performance and overhead advantages.
This is to be done by some people.