简体   繁体   中英

C# Threading and Memory Leaks

I am writing an application that opens Microsoft Excel through Interop.

The problem I am having is if the application itself Locks Up or Memory Leaks, my application becomes blocked and will not continue the thread.

I have a parent thread that looks at a directory and writes in a loop for each file

Convert("src.xls","src.pdf",null); And some times say for example if we give excel a file type it cannot open it will lock up. Which will lock my thread forcing me to have to kill the process.

public static class ExcelConverter
{
    public static bool Convert(string srcFile, string destinationFile, object[] parameters)
    {
        bool bStatus = false;
        Workbook excelWorkBook = null;
        Excel.Application application = null;

        try
        {


        application = new Excel.Application();
        object missingParam = Type.Missing;


            excelWorkBook = application.Workbooks.Open(srcFile);

            if (excelWorkBook != null)
            {
                excelWorkBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, destinationFile);
            }
            bStatus = true;
        }
        catch (Exception)
        {

            bStatus = false;
        }
        finally
        {
            if (excelWorkBook != null)
            {
                excelWorkBook.Close(false);
                excelWorkBook = null;
            }

            if (application != null)
            {
                application.Quit();
                application = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        return bStatus;
    }
}

for example if we give excel a file type it cannot open it will lock up

It is probably trying to display a dialog that tells the user about it. Debug this by setting application.Visible = true so you can actually see the dialog. Fix it by specifying more arguments in the Open() call. The Password, Notify and CorruptLoad arguments have an effect. Screening the files better is an obvious workaround, Excel is really designed to be interactive and chatty about problems.

You don't have too much to fear from threads, Excel is a single-threaded COM object and COM makes sure that the interface methods are called in a thread-safe way. Which is does in your case by actually creating a new thread to give the interop object a safe home.

Here you may want to create an object that extends MarshalByRefObject object that you can spawn in a new AppDomain to do the conversion. When done, just unload the AppDomain and all the memory will be cleared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM