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(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP