473,698 Members | 2,283 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

excel process not terminating properly

hello all you gurus. I am struggling with releasing com objects. I
have isolated the problem to the code below. Objects are released and
the process ends until I
use "int k = sheet.Count;" Then the process does not end. So I feel
confident the problem occurrs here. It appears another reference is
created that needs to be closed. Can anyone tell me how to do
this? :)
Thank you

Excel.Workbook workbook =
(Excel.Workbook )excelapplicati on.ActiveWorkbo ok;
Excel.Sheets sheet = workbook.Worksh eets;

// problem here
int k = sheet.Count;

System.Runtime. InteropServices .Marshal.Releas eComObject(shee t);
sheet = null;
System.Runtime. InteropServices .Marshal.Releas eComObject(work book);
workbook = null;

Apr 18 '07
13 1186
On Apr 18, 5:38 pm, "Willy Denoyette [MVP]"
<willy.denoye.. .@telenet.bewro te:
<chuckie_9...@h otmail.comwrote in message

news:11******** **************@ b58g2000hsg.goo glegroups.com.. .


On Apr 18, 3:48 pm, "Herfried K. Wagner [MVP]" <hirf-spam-me-
h...@gmx.atwrot e:
<chuckie_9...@h otmail.comschri eb:
I am struggling with releasing com objects. I
have isolated the problem to the code below. Objects are released and
the process ends until I
use "int k = sheet.Count;" Then the process does not end.
PRB: Office Application Does Not Quit After Automation from Visual Studio
.NET Client
<URL:http://support.microso ft.com/?scid=kb;EN-US;317109>
-"Troubleshootin g"
--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
thank you for your resposnse and I have to admit I am somewhat
confused (I guess that's obvious). I read the article and maybe I
missed the obvious, but I do use GC.Collect() and
GC.WaitForPendi ngFinalizers() and excelapplicatio n.quit(). And I
think I understand that I must explicitly reference any object that is
implicitly created. So, I think (I am probably wrong) int k =
sheet.Count; creates an implicit reference that I must explicitly
reference so I can remove the reference. Is this correct? If so , how
do I do that? If I am wrong, please correct me. Everything works
fine until this statement is added. Thank you

No, Count does not create an reference to a COM object, sheet holds a reference to the COM
interface.
But as long as you don't post a *complete* sample, that illustrates the issue, you won't get
any sensible answers.

A complete sample looks something like this:

using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Globaliz ation;
using System.Reflecti on;

using Exl = Microsoft.Offic e.Interop.Excel ;
namespace OffExc
{
class Program
{
[STAThread]
static void Main(string[] args)
{
System.Threadin g.Thread.Curren tThread.Current Culture = new CultureInfo( "en-US",
false );
Exl.Application exApp = new Microsoft.Offic e.Interop.Excel .ApplicationCla ss();
// Reference 1
Exl.Workbook wb = exApp.Workbooks .Add(Missing.Va lue); // Reference 2
exApp.Visible = true;
// Keep Excel visible for a while..
System.Threadin g.Thread.Sleep( 3000);
Exl.Sheets sheet = wb.Worksheets; // // Reference 3
int k = sheet.Count;
// Quit
exApp.Quit();
// Release the three COM references...
System.Runtime. InteropServices .Marshal.Releas eComObject(shee t);
System.Runtime. InteropServices .Marshal.Releas eComObject(wb);
System.Runtime. InteropServices .Marshal.Releas eComObject(exAp p);
GC.Collect();
// Let the finalizer run, this one will delete the unmanaged COM wrappers,
// if for one or another reason, the finalizer cannot run to completion,
// chances are that the Excel process won't get removed !!!!!!!!
GC.WaitForPendi ngFinalizers();
// Excel should be gone by now... keep the console processrunning for a while
System.Threadin g.Thread.Sleep( 30000);
}
}

}

And above code works as expected on my box.

Willy.- Hide quoted text -

- Show quoted text -
thank you gentlmen for your help. the following seems to be working
correctly. of course I have alot more to do but this will get me
started. Is there a "better" way to save the workbook (ie, use
wb.saveas) and is there a better way way to enumerate and delete
unwanted sheets? Also, I realize error checking needs to be
implemented. Thanks again for your assistance.

using System;
using System.Reflecti on;
using System.Threadin g;
using System.Globaliz ation;
using Exl = Microsoft.Offic e.Interop.Excel ;

namespace mynamespace
{
class myexcel
{
public void test()
{
System.Threadin g.Thread.Curren tThread.Current Culture = new
CultureInfo("en-US", false);
Exl.Application exApp = new
Microsoft.Offic e.Interop.Excel .ApplicationCla ss();
// Reference 1
Exl.Workbook wb = exApp.Workbooks .Add(Missing.Va lue); //
Reference 2
exApp.Visible = true;
Exl.Sheets sheet = wb.Worksheets; // Reference 3
// set active sheet
Exl.Worksheet activesheet = (Exl.Worksheet) wb.ActiveSheet;
activesheet.Nam e = "testsheet" ;
// write to cell A1
Exl.Range range;
range = activesheet.get _Range("A1", Missing.Value);
range.Value2 = "test input";

System.Runtime. InteropServices .Marshal.Releas eComObject(rang e);
// disable alerts so I'm not prompted when a worksheet is
deleted
exApp.DisplayAl erts = false;
// delete a sheet
for (int i = 1; i <= sheet.Count; i++)
{
// would like to delete
Exl.Worksheet ob = (Exl.Worksheet) exApp.Worksheet s[i];
if (ob.Name.ToLowe r().Substring(0 , 5).Equals("shee t"))
ob.Delete();
ReleaseComObjec t(ob);
ob = null;
}
// save the workbook
exApp.ActiveWor kbook.Close(tru e, @"c:\testxls.xl s",
Missing.Value);
// Quit
exApp.Quit();
// Release the COM references...
ReleaseComObjec t(activesheet);
ReleaseComObjec t(sheet);
ReleaseComObjec t(wb);
ReleaseComObjec t(exApp);
GC.Collect();
// Let the finalizer run, this one will delete the unmanaged
COM wrappers,
// if for one or another reason, the finalizer cannot run to
completion,
// chances are that the Excel process won't get
removed !!!!!!!!
GC.WaitForPendi ngFinalizers();
// Excel should be gone by now... keep the console
processrunning for a while
System.Threadin g.Thread.Sleep( 3000);
}
public void ReleaseComObjec t(Object reference)
{
try
{
while
(System.Runtime .InteropService s.Marshal.Relea seComObject(ref erence) >
-1) ;
}
catch (Exception ex)
{
// handle exception
}
finally
{
reference = null;
}
}
}
}


Apr 19 '07 #11
By more elaborate, I just meant that they've broken the release of the
object into a separate function. It seems that the OP is doing the same
thing in his code, just not in a separate function. What, exactly, is the
article showing that the OP isn't doing?
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.atwrote in message
news:ON******** ******@TK2MSFTN GP06.phx.gbl...
"Scott M." <s-***@nospam.nosp amschrieb:
>Your link shows (in a more elaborate way) how to do what the OP is
already doing (RleaseCOMObjec t and set to null). Is there a particular
part of the article that you suggest?

I suggest the "more elaborate way".

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Apr 19 '07 #12
"Scott M." <s-***@nospam.nosp amschrieb:
By more elaborate, I just meant that they've broken the release of the
object into a separate function. It seems that the OP is doing the same
thing in his code, just not in a separate function. What, exactly, is the
article showing that the OP isn't doing?
Take a look at the information in the "Troubleshootin g" section of the
document.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Apr 19 '07 #13
<ch**********@h otmail.comwrote in message
news:11******** **************@ q75g2000hsh.goo glegroups.com.. .
On Apr 18, 5:38 pm, "Willy Denoyette [MVP]"
<willy.denoye.. .@telenet.bewro te:
><chuckie_9...@ hotmail.comwrot e in message

news:11******* *************** @b58g2000hsg.go oglegroups.com. ..


On Apr 18, 3:48 pm, "Herfried K. Wagner [MVP]" <hirf-spam-me-
h...@gmx.atwrot e:
<chuckie_9...@ hotmail.comschr ieb:
I am struggling with releasing com objects. I
have isolated the problem to the code below. Objects are released and
the process ends until I
use "int k = sheet.Count;" Then the process does not end.
>PRB: Office Application Does Not Quit After Automation from Visual Studio
.NET Client
<URL:http://support.microso ft.com/?scid=kb;EN-US;317109>
-"Troubleshootin g"
>--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
thank you for your resposnse and I have to admit I am somewhat
confused (I guess that's obvious). I read the article and maybe I
missed the obvious, but I do use GC.Collect() and
GC.WaitForPendi ngFinalizers() and excelapplicatio n.quit(). And I
think I understand that I must explicitly reference any object that is
implicitly created. So, I think (I am probably wrong) int k =
sheet.Count; creates an implicit reference that I must explicitly
reference so I can remove the reference. Is this correct? If so , how
do I do that? If I am wrong, please correct me. Everything works
fine until this statement is added. Thank you

No, Count does not create an reference to a COM object, sheet holds a reference to the
COM
interface.
But as long as you don't post a *complete* sample, that illustrates the issue, you won't
get
any sensible answers.

A complete sample looks something like this:

using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Globaliz ation;
using System.Reflecti on;

using Exl = Microsoft.Offic e.Interop.Excel ;
namespace OffExc
{
class Program
{
[STAThread]
static void Main(string[] args)
{
System.Threadin g.Thread.Curren tThread.Current Culture = new CultureInfo(
"en-US",
false );
Exl.Application exApp = new
Microsoft.Offi ce.Interop.Exce l.ApplicationCl ass();
// Reference 1
Exl.Workbook wb = exApp.Workbooks .Add(Missing.Va lue); // Reference 2
exApp.Visible = true;
// Keep Excel visible for a while..
System.Threadin g.Thread.Sleep( 3000);
Exl.Sheets sheet = wb.Worksheets; // // Reference 3
int k = sheet.Count;
// Quit
exApp.Quit();
// Release the three COM references...
System.Runtime. InteropServices .Marshal.Releas eComObject(shee t);
System.Runtime. InteropServices .Marshal.Releas eComObject(wb);
System.Runtime. InteropServices .Marshal.Releas eComObject(exAp p);
GC.Collect();
// Let the finalizer run, this one will delete the unmanaged COM wrappers,
// if for one or another reason, the finalizer cannot run to completion,
// chances are that the Excel process won't get removed !!!!!!!!
GC.WaitForPendi ngFinalizers();
// Excel should be gone by now... keep the console processrunning for a while
System.Threadin g.Thread.Sleep( 30000);
}
}

}

And above code works as expected on my box.

Willy.- Hide quoted text -

- Show quoted text -

thank you gentlmen for your help. the following seems to be working
correctly. of course I have alot more to do but this will get me
started. Is there a "better" way to save the workbook (ie, use
wb.saveas) and is there a better way way to enumerate and delete
unwanted sheets? Also, I realize error checking needs to be
implemented. Thanks again for your assistance.

using System;
using System.Reflecti on;
using System.Threadin g;
using System.Globaliz ation;
using Exl = Microsoft.Offic e.Interop.Excel ;

namespace mynamespace
{
class myexcel
{
public void test()
{
System.Threadin g.Thread.Curren tThread.Current Culture = new
CultureInfo("en-US", false);
Exl.Application exApp = new
Microsoft.Offic e.Interop.Excel .ApplicationCla ss();
// Reference 1
Exl.Workbook wb = exApp.Workbooks .Add(Missing.Va lue); //
Reference 2
exApp.Visible = true;
Exl.Sheets sheet = wb.Worksheets; // Reference 3
// set active sheet
Exl.Worksheet activesheet = (Exl.Worksheet) wb.ActiveSheet;
activesheet.Nam e = "testsheet" ;
// write to cell A1
Exl.Range range;
range = activesheet.get _Range("A1", Missing.Value);
range.Value2 = "test input";

System.Runtime. InteropServices .Marshal.Releas eComObject(rang e);
// disable alerts so I'm not prompted when a worksheet is
deleted
exApp.DisplayAl erts = false;
// delete a sheet
for (int i = 1; i <= sheet.Count; i++)
{
// would like to delete
Exl.Worksheet ob = (Exl.Worksheet) exApp.Worksheet s[i];
if (ob.Name.ToLowe r().Substring(0 , 5).Equals("shee t"))
ob.Delete();
ReleaseComObjec t(ob);
ob = null;
}
// save the workbook
exApp.ActiveWor kbook.Close(tru e, @"c:\testxls.xl s",
Missing.Value);
// Quit
exApp.Quit();
// Release the COM references...
ReleaseComObjec t(activesheet);
ReleaseComObjec t(sheet);
ReleaseComObjec t(wb);
ReleaseComObjec t(exApp);
GC.Collect();
// Let the finalizer run, this one will delete the unmanaged
COM wrappers,
// if for one or another reason, the finalizer cannot run to
completion,
// chances are that the Excel process won't get
removed !!!!!!!!
GC.WaitForPendi ngFinalizers();
// Excel should be gone by now... keep the console
processrunning for a while
System.Threadin g.Thread.Sleep( 3000);
}
public void ReleaseComObjec t(Object reference)
{
try
{
while
(System.Runtime .InteropService s.Marshal.Relea seComObject(ref erence) >
-1) ;
}
catch (Exception ex)
{
// handle exception
}
finally
{
reference = null;
}
}
}
}


No need to make it that complicated, each sheet will share the same COM object reference,
that means that you only have to release it once when done.

// delete default sheets
Exl.Worksheet ob = null;
for (int i = 1; i <= sheet.Count; i++)
{
// would like to delete
ob = (Exl.Worksheet) exApp.Worksheet s[i];
if(ob.Name.Star tsWith("Sheet") ) ob.Delete();
}
// release the single Worksheet COM interface used by ob ...
System.Runtime. InteropServices .Marshal.Releas eComObject(ob);
// create new sheet...
No need for the ReleaseComObjec t method either.

Willy.

Apr 19 '07 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8369
by: David Berman | last post by:
Hi, I've written an application to do a while bunch of Excel automation. I open a file, scan through all the worksheets, extract data, and then I try to close Excel. However, I can see that I'm not doing it effectively. If I am debugging my app, and I kill the app before my app exits, but after the call that should close excel, I still have an excell process sitting around. After about 20 + of those stack up, you start to feel it. If I...
2
402
by: Mark | last post by:
Hi all, as many had, i have some problems terminating the excel-process. I implemented the solutions i found in this forums. Tried most combinations of them ;-). It still doesn't work. I'll post my code-snippets below. I hope u can shine some light on the solution.
2
21945
by: Powerguy | last post by:
Hi all, I am looking for a way to get the Process id (or a handle) of an EXCEL process created from within my code. For example when the following code is executed: Dim EXL As Excel.Application = New Excel.Application a new instance of EXCEL.EXE is created in the task manager.
18
3088
by: lgbjr | last post by:
Hi All, I have a VB.NET app that, among other things, writes data to Excel. I am having trouble getting the Excel process to terminate after I quit Excel. I found an article related to this problem: http://support.microsoft.com/default.aspx?scid=kb;en-us;317109 Below is a sample of code that I wrote based on the above article. The excel workbook, worksheets, and all of the cells are properly formatted when Excel
13
3008
by: chuckie_9497 | last post by:
hello all you gurus. I am struggling with releasing com objects. I have isolated the problem to the code below. Objects are released and the process ends until I use "int k = sheet.Count;" Then the process does not end. So I feel confident the problem occurrs here. It appears another reference is created that needs to be closed. Can anyone tell me how to do this? :) Thank you Excel.Workbook workbook =
0
1300
by: ravindarjobs | last post by:
dear friends, i am using ms access 2003. i wanted to export data from access table to excel table. so i have followed this Dim db As Database Dim ea As Excel.Application Dim rs As Recordset
0
8676
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8608
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9029
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8898
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8870
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7734
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6524
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.