Prevent Excel Application from hanging when using Microsoft Excel Interop DLL in Windows Application

Last Reply 13 days ago By dharmendr

Posted 13 days ago

Hi,

How to Avoid Application getting hanged while working with Excel

But the problem with code is application is getting hanged when the control comes to the line

Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

I have below method which opens Excel (macro) in a windows application. 

        internal void CEGForm(Project project, int quotationNo, string currencyCode, string reportname)
        {            
            Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook excelWorkbook = excelApp.Workbooks.Open(Application.StartupPath + "\\" + ReportNames.CEGRequestForm_Template);
            try
            {
                var reportPath = GetPathToGenerateReport(reportname + ".xlsm");
                if (File.Exists(reportPath))
                    File.Delete(reportPath);

                excelWorkbook.SaveAs(new FileInfo(reportPath));
                excelApp.Workbooks.Close();
                excelApp = null;
                CommonExtensionFunctions.ProcessStart(reportPath);
            }
        }
        private  string GetPathToGenerateReport(string reportName)
        {
            return Path.Combine(Path.GetTempPath(), reportName); //Use system temp folder.
        }

It is also getting hanged at next line

Workbook excelWorkbook = excelApp.Workbooks.Open(Application.StartupPath + "\\" + ReportNames.CEGRequestForm_Template); 

I thought of writing Thread.Sleep(1000); after above 2 lines, like below

Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Thread.Sleep(1000);

But I think, there will be more efficient way to handle this kind of scenario, may be using Aync and Await.

If Aync and Await, is the right approach, can someone help me how to implement the same.

Thanks.

You are viewing reply posted by: dharmendr 13 days ago.