Good day to all! There is a code which from Excel transfers all data to the form in dataGridView1. Naturally, after working with Excel, you need to unload all his junk so that he does not hang in the processes. All code was in button_Click. The upload worked and the process terminated correctly right after execution. It was necessary to transfer all the code to the function and call it on click. Transferred and the process remains hanging in the task processor. Googled and found nothing What am I doing wrong? Code.
private void button3_Click(object sender, EventArgs e) { test(); } public void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; } finally { GC.Collect(); } } public void test() { dsTest dSet = new dsTest(); Excel.Application ExcelApp = new Excel.Application(); Excel.Worksheet ExcelWorkSheet; Excel.Workbook ExcelWorkBook; Excel.Range ExcelRange; var workbooks = ExcelApp.Workbooks; ExcelWorkBook = workbooks.Open(@"D:\\Эксель.xlsm", 0, false); ExcelWorkSheet = ExcelWorkBook.ActiveSheet; ExcelRange = ExcelWorkSheet.UsedRange; for (int Rnum = 2; Rnum <= ExcelRange.Rows.Count - 2; Rnum++) { DataRow dr = dSet.DataTable1.NewRow(); for (int Cnum = 1; Cnum <= ExcelRange.Columns.Count; Cnum++) { if ((ExcelRange.Cells[Rnum, Cnum] as Excel.Range).Value2 != null) { dr[Cnum - 1] = (ExcelRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString(); } } dSet.DataTable1.Rows.Add(dr); dSet.DataTable1.AcceptChanges(); } dataGridView1.DataSource = dSet.DataTable1; dataGridView1.Visible = true; ExcelWorkBook.Close(true, null, null); ExcelApp.Quit(); releaseObject(ExcelApp); releaseObject(workbooks); releaseObject(ExcelWorkBook); releaseObject(ExcelWorkSheet); releaseObject(ExcelRange); } Previously, all that was in test () was in button3_Click and the process was completed, but in this way it remains to hang.