You may face “DisconnectedContext was detected” error if you work with Excel interop objects in C#. This error causes crashing your application. It is really annoying issue and there is no specific resolution for this. So, I’ll give the general idea in this post.
Context 0xdf76a0′ is disconnected. Releasing the interfaces from the current context (context 0xdf7450). This may cause corruption or data loss. To avoid this problem, please ensure that all contexts/apartments stay alive until the application is completely done with the RuntimeCallableWrappers that represent COM components that live inside them.
Your code may look like this:
Excel._Application app = new Excel.Application(); Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); Excel._Worksheet worksheet = null; app.Visible = true; worksheet.Cells[1, 1] = "test string"; workbook.SaveAs("C:\testfile.xlsx"); object misValue = System.Reflection.Missing.Value; workbook.Close(true, misValue, misValue); app.Quit(); releaseObject(worksheet); releaseObject(workbook); releaseObject(app);
At the first time the debugger goes into releaseObject, it gives DisconnectedContext
error at first GC.WaitForPendingFinalizers()
line in my case.
Solution
This issue has a quite complicated background. In order to simplify it, I wrote a post that is related to this problem a few days ago. Check this out:
https://port135.com/2012/08/08/how-to-properly-clean-up-excel-interop-objects-in-c/
If it doesn’t help:
- Make sure you release all objects accurately. Study Runtime Callable Wrapper and ReleaseComObject.
- Try to run your application in “release mode” instead of “debug mode“. Sometime this error doesn’t show up in “release mode”. So, you may want not to do anything about it.
- If the problem is still going on, publish your application (Project > Properties > Publish). Do you have the same problem? If you don’t, it doesn’t mean you have resolved it. You have just ignored it. If you want to resolve it forever, go back to step 1 and try hard.
Good comments and advise which I will try. Your post is missing because the link is bad, the domain has gone
I updated the link. Thanks for letting me know.