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

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…