We help IT Professionals succeed at work.

Disconnected Context Using Excel Automation

EdwardAF
EdwardAF used Ask the Experts™
on
I recently finished writing a routine to apply processing to an Excel file through VB.NET using the automation API.  The code works fine, and it is called repeatedly for about 60 work items.  In other words, about 60 reports are being rendered from rdlc to Excel, and then those 60 files are processed one by one using this routine.

At about the 60% or 70% mark during processing, which is usually between 15 and 20 minutes into the process, the following exception is thrown:

DisconnectedContext was detected
Message: Context 0x198388' is disconnected.  Releasing the interfaces from the current context (context 0x1984f8).This may cause corruption or data loss. To avoid this problem, please ensure that all contexts/apartments stay alive until the applicationis completely done with the RuntimeCallableWrappers that represent COM components that liveinside them.

I am not a COM expert, and it sounds like this is a COM error.  I am only using COM to the extent needed to make use of Excel automation.

What is this exception, and how can I keep this from happening until all of the processing is complete?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2014

Commented:
Looks like timeout to me.

Author

Commented:
How do we stop the timeout?
Most Valuable Expert 2012
Top Expert 2014
Commented:
Seems to be a complex issue. Make sure you do not try to access Excel when its been shut

http://msdn.microsoft.com/en-us/library/2c1czate.aspx

Author

Commented:
I have tried running the app completey hands-off - not touching Excel or even the mouse.  It still throws this error at about the same time as before.  Any other ideas?
Commented:
I've figured it out.  Apparently, when the outside process (in this case, Excel) runs for too long, the OS thinks it has taken over and not letting other applications run.  The diagnosis was dreadful, but the solution is very simple.  Add the following line of code in one or more places to allow other processes to execute, and now the long execution completes without issue.

System.Windows.Forms.Application.DoEvents()

Author

Commented:
This link gave me some other places to look but did not in and of itself resolve the issue.