This is in continuation to my previous question (Open Excel Workbook with vba code – error to notify VSTO) which is yet to be resolved. I have a fresh set of problem with Excel Interop.
Even without any error in the excel file I see that workBooks.Open sometimes hangs indefinitely thus causing my application to hang forever. I am using the following code to initialize the excel object
public static class InterOpService
{
private static Application _excel;
public static Application Excel
{
get
{
try
{
_excel = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
_excel.Visible = true;
}
catch(Exception ex)
{
_excel = new Application { Visible = true };
}
return _excel;
}
}
}
The above code returns me an Excel object. It also tries to avoid creating multiple instances of Excel object. The following code uses this returned object
Application excel = InterOpService.Excel;
Workbooks workBooks = excel.Workbooks;
string file = fileName;
Workbook workBook = workBooks.Open(file, 0,
true,
5,
"",
"",
true,
XlPlatform.xlWindows,
"\t",
false,
false,
0,
true,
1,
0);
One probable reason I see to thi hanging of workbooks.open is file sharing. Probably an antivirus scanner is getting the exclusive lock onto the file and my app is hanging while trying to Open at that time. The problem is this is a random behavior and I am really struggling to replicate this.Another problem is I have to find a way out with Interop only.
I found the issue.
Following were the reasons for hanging:
1) I was opening the workbook over the network.
file was not in my local machine. The number of cases with hanging reduced after I copied the file to local machine and did the open.
2) Server memory.
Another reason for hanging was that the CPU usage in the server was 100%.Not in my control. But satisfied that I hunted this down.
The main problem with Open method is that it is not responsive enough to let the caller know about these reasons. The best way is, to do this activity in a thread and give the thread sometime to execute. Fail, if the thread does not respond in the specified time frame.