Skip to main content

Interop - release COM objects( Excel.EXE hanging)

Pentru mine "interopul" a fost mereu o provocare. Nu neaparat modul prin care se pot face apelurile ci modul in care se face dispose la acestea si eliberarea resurselor.
O sa ma duc pe un exemplu concret - interopul cu Excel. Cand lucram cu acesta viata noastra poate sa devina un iad daca nu eliberam resursele corespunzator. Daca avem un serviciu windows care proceseaza fisiere Excel, foarte usor ne putem trezii ca avem 100 de procese EXCEL.EXE ramase agatate in sistem cu care nu stim ce sa facem. Dar asta nu e tot, fisierele raman agate pe disk pana cand cineva omoara procesul.
Sa incepem cu inceputul. Pentru a putea accesa un fisier Excel folosind Microsoft Office, avem un cod asemanator cu acesta:
Application application = new Application()
{
Visible = false,
UserControl = true,
};
Workbook workbook = Application.Workbooks.Open(fileName, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t",true,false, 0, true, 1, 0);
Worksheet worksheet = (Worksheet)Workbook.Worksheets.Item[1];
Range range = Worksheet.UsedRange;
.....
string value = (range.Cells[rowNumber, columnNumber] as Range).Text;
Pentru fiecare obiect din Office trebuie sa facem explicit dispose folosind
"System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)".
Trebuie avuta mare grija, deoarece in exemplul dat mai sus ultima linie de cod contine un obiect la care o sa pierdem referinta si la care nu o sa mai putem face dispose:
range.Cells[rowNumber, columnNumber] as Range
Un apel corect, care o sa ne permita sa facem si dispose ar fi:
Range cell = range.Cells[rowNumber, columnNumber] as Range;
string value = cell.Text;
In acest fel o sa putem face release si la obiectul care are o referinta la celula pe care o procesam.
Inainte sa facem release la Workbook si Application este nevoie sa le inchidem si sa facem quit pe ele:
workbook.Close(false, Type.Missing, Type.Missing);
Application.Application.Quit();
Application.Quit();
O implementare a metodei care face release pentru exemplul nostru ar putea sa fie urmatoarea:
System.Runtime.InteropServices.Marshal.ReleaseComObject(cell);
workbook.Close(false, Type.Missing, Type.Missing);
Application.Application.Quit();
Application.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
GC.Collect();
GC.WaitForPendingFinalizers();
Dupa cum se poate observa toate actiunile care se fac sunt destul de complexe si trebuie avut grija ca sa se face release la fie obiect in parte. Daca nu eliberam aceste resurse o sa ne trezim cu procese de tip EXCEL.exe ramane in memorie la care trebuie sa facem manual dispose( kill). Ca sa ne usuram putin viata putem sa ne definim o clasa generica care sa faca release automat la obictele din COM.
public class AutoReleaseComObject<TComObject> : IDisposable
where TComObject : class
{
private TComObject _comObject;
private bool _disposed = false;

public AutoReleaseComObject(TComObject comObject)
{
_comObject = comObject;
}

public TComObject ComObject
{
get { return _comObject; }
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
lock (this)
{
if (_disposed)
{
return;
}

int refcnt = 0;
do
{
refcnt = System.Runtime.InteropServices.Marshal.ReleaseComObject(_comObject);
} while (refcnt > 0);

_comObject = default(TComObject);
_disposed = true;
}
}
}
Cam asa ar arata implementarea pentru un obiect COM. Daca aveam nevoie sa facem si alte actiuni, asa cum facem pentru Application, putem sa face ovverite la metoda Dispose si sa facem intr-un alt mod eliberarea de resurse.
Totul o sa fie bine pana cand un alt dezvoltator o sa vina si o sa ne modifice codul cand fara sa isi dea seama nu o sa faca release la resurse. De exemplu in urmatoarea line de cod:
((Range)range.get_Value(rangeValueDataType)).QueryTable.Creator
se pierde referinta la doua obiecte la care nu o sa se mai poata face dispose. Prima greseala este obiectul returnat de 'get_Value', la care trebuie sa se faca dispose. Al doilea obiect este QueryTable unde apare aceiasi problema. Corect ar trebui sa avem:
Range itemRange = (Range)Range.get_Value(rangeValueDataType);
QueryTable queryTable = itemRange.QueryTable;
XlCreator creator = queryTable.Creator;
Daca folosim solutie prezentata putin mai sus am obtine urmatorul cod:
using (AutoReleaseComObject<Range> range=GetRange())
{
using (AutoReleaseComObject<Range> itemRange = range.ComObject.get_Value(rangeValueDataType))
{
using (AutoReleaseComObject<QueryTable> queryTable = itemRange.ComObject.QueryTable)
{
XlCreator creator = queryTable.Creator;
}
}
}
Si totusi sunt diferite cazuri cand un obiect COM ne scapa si ne trezim cu un proces agatat. Exista si diferite probleme cu inteoropul de Office din cauza carora nu se poate face release la date corespunzator si ne trezim ca nu putem sa scapam de proces.
O solutie destul de hard-core, care trebuie folosita cu mare grija este sa omoram direct procesul. In exemplul de mai jos o sa obtin Hwnd( adrsa din memorie) din procesul EXCEL.exe pe baza caruia putem obtine id-ul procesului EXCEL.EXE pe care dorim sa il omoram.
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
...
int currentHWn =application.Hwnd
uint processID;
GetWindowThreadProcessId((IntPtr)hWnd, out processID);
if (processID != 0)
{
Process.GetProcessById((int)processID).Kill();
}
O alternativa la interop pentru Office este Open XML: http://msdn.microsoft.com/en-us/library/bb448854%28office.14%29.aspx
Succes!

Comments

  1. De asta tot zice Microsoft-ul - nu folositi office automation server-side :-) : http://support.microsoft.com/kb/257757

    Da, se poate, da' nu merita chinul daca firma isi permite sa cumpere o componenta specializata in asa ceva sau eventual chestii gen Excel Services de la Microsoft..

    ReplyDelete
  2. 1. Aspose e ieftin
    2. Daca faci Marshall.ReleaseComObject si nu faci allow la doua puncte, merge!

    ReplyDelete

Post a Comment

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...