2012-06-27 2 views
3

가능한 중복 :
How to properly clean up Excel interop objects in C#내 Excel 사무실 개체가 EXCEL.exe 프로세스 뒤에 남겨두고있는 이유는 무엇입니까?

나는 C#을 용 Office Interop를 라이브러리를 사용하는 응용 프로그램이 있습니다.

이 라이브러리는 IIS7에서 호스팅되는 ASP.NET 응용 프로그램에서 호출됩니다.

관련 코드 비트는 다음과 같습니다

/// <summary> 
/// Provides excel functions. 
/// </summary> 
public class ExcelStuff : IDisposable 
{ 
    #region Excel Components 

    // The following are pre-allocated Excel objects that must be explicitly disposed of. 

    private Excel.Application xApp; 
    private Excel.Workbooks xWorkbooks; 
    private Excel.Workbook xWorkbook; 
    private Excel.Sheets xWorksheets; 
    private Excel.Worksheet xWorksheet; 
    private Excel.ChartObjects xCharts; 
    private Excel.ChartObject xMyChart; 
    private Excel.Chart xGraph; 
    private Excel.SeriesCollection xSeriesColl; 
    private Excel.Series xSeries; 

    #endregion 

    /// <summary> 
    /// Initializes a new instance of the <see cref="ExcelStuff" /> class. 
    /// </summary> 
    public ExcelStuff() 
    { 
    } 

    /// <summary> 
    /// Does some work. 
    /// </summary> 
    public void DoWork() 
    { 
     byte[] data = new byte[0]; 

     worker = new Thread(() => 
     { 
      // Do some work. 
     }); 

     worker.Start(); 
     worker.Join(); 

     worker.Abort(); 
     worker = null; 

     Dispose(); 
    } 

    /// <summary> 
    /// Disposes the current object and cleans up any resources. 
    /// </summary> 
    public void Dispose() 
    { 
     // Cleanup 
     xWorkbook.Close(false); 
     xApp.Quit(); 

     // Manual disposal because of COM 
     xApp = null; 
     xWorkbook = null; 
     xWorksheets = null; 
     xWorksheet = null; 
     xCharts = null; 
     xMyChart = null; 
     xGraph = null; 
     xSeriesColl = null; 
     xSeries = null; 

     GC.Collect(); 
    } 
} 

당신은이 문제를 해결하기 위해 내 필사적 인 시도를있는 코드의 중복, 많이 알 수 있습니다. GC.Collect()을 호출하는 것이 비효율적이거나 클래스 내에서 Dispose()을 호출하는 것이 좋지 않다고 말하지 마십시오. 이미 이러한 사실을 알고 있습니다.

내가 알고 싶은 것은 왜 가능한 한 많은 개체를 정리할 때이 코드가 고아 인 EXCEL.exe 프로세스가 서버에서 실행되고 있는지입니다.

+3

참조 http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c-sharp Marhsal.ReleaseComObject is 네 친구. – dash

+0

이거 봤어? http://stackoverflow.com/q/1884217/88672 – mgnoonan

+0

Microsoft는이 작업을 수행하지 말라고 권고합니다. 여기에 수락 된 대답에서 토론 및 링크를 참조하십시오. http://forums.asp.net/t/1804781.aspx/1 – Bill

답변

3

의견에서 언급 한 누군가가 Marshal.ReleaseComObject를 사용하여 Excel 개체를 정리합니다. 다음은 내 코드 샘플입니다.

 wb.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value); 

     while (System.Runtime.InteropServices.Marshal.ReleaseComObject(wb) != 0) 
     { } 

     excelApp.Quit(); 

     while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp) != 0) 
     { } 

이것은 나를위한 것 같습니다. 행운을 빕니다!

편집 : 죄송합니다. 이것이 중복이라고 생각하지 않았습니다. 개조는 이걸로 무엇이든 할 수 있습니다 ...

+0

걱정 마세요, 어쨌든 받아 들였습니다. 정답입니다. – qJake

관련 문제