Many "excel" processes shown on the task manager - processes
Even when my app closes and finishes, when I watch on my task manager -> processes, there are many excel processes which even prevent my computer from shutting down.
Here is my code:
private void write_data_to_excel(byte[] input)
{
FileStream f = File.OpenWrite("StocksData.xls");
f.Write(input, 0, input.Length);
f.Close();
}
Another possible method who causes this:
private void get_stocks_data()
{
byte[] result;
byte[] buffer = new byte[4096];
try
{
WebRequest wr = WebRequest.Create("http://www.tase.co.il/TASE/Pages/ExcelExport.aspx?sn=none&enumTblType=allShares&Columns=noneColumns&Titles=noneTitles&action=1&SubAction=0&GridId=33&CurGuid={0BDA5110-EF93-44CB-A0F0-468C6F502B51}&ExportType=1");
using (WebResponse response = wr.GetResponse())
{
using (Stream responseStream = response.Get开发者_如何学PythonResponseStream())
{
using (MemoryStream memoryStream = new MemoryStream())
{
int count = 0;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);
} while (count != 0);
result = memoryStream.ToArray();
write_data_to_excel(result);
}
}
}
}
My code also contains:
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(file, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
These methods are called priodicly... What am I not closing or...?
Take a look at How to properly clean up Excel Interop objects in C#. You need to be very careful about cleaning up all the COM objects when using the Excel Interop. The accepted answer in the post will explain why what you are doing is causing the process to stay open. The main point is to Never use 2 dots with com objects.
You need a try/catch around the code that opens the Excel application and any workbooks, and a finally
block that closes open workbooks and quits the application:
finally
{
if (wb != null) wb.Close();
if (app != null) app.Quit();
app = null;
}
Note that if you're debugging your code and stop the debugger in the middle, you'll still have the Excel process because your finally
block will not execute.
The most solid way I've found to do this is to release each worksheet within the workbook using:
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
and then release the Excel app using the same call:
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
then to do:
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
Sometimes, when the COM applications leak, a call to Marshal.ReleaseComObject() solves the problem
精彩评论