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(

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provided a too