Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine when a .NET thread terminates?

I'm trying to find out whether there is a way to reliably determine when a managed thread is about to terminate. I'm using a third-party library that includes support for PDF documents and the problem is that in order to use the PDF functionality, I have to explicitly initialize the PDF component, do the work, then explicitly uninitialize the component before the thread terminates. If the uninitialize is not called, exceptions are thrown because unmanaged resources are not being released correctly. Since the thread class is sealed and has no events, I have to wrap the thread instance into a class and only allow instances of this class to do the work.

I should point out that this is part of a shared library used by multiple Windows applications. I may not always have control of threads making calls into this library.

Since a PDF object may be the output of a call to this library, and since the calling thread may do some other work with that object, I don't want to call the cleanup function immediately; I need to try to do it right before the thread terminates. Ideally I'd like to be able to subscribe to something like a Thread.Dispose event, but that's what I'm missing.

like image 472
mullala Avatar asked Sep 30 '08 14:09

mullala


1 Answers

You don't want to wrap System.Thread per se - just compose it with your PDFWidget class that is doing the work:

class PDFWidget
{
    private Thread pdfWorker;
    public void DoPDFStuff()
    {
        pdfWorker = new Thread(new ThreadStart(ProcessPDF));
        pdfWorker.Start();
    }

    private void ProcessPDF()
    {
        OtherGuysPDFThingie pdfLibrary = new OtherGuysPDFThingie();
        // Use the library to do whatever...
        pdfLibrary.Cleanup();
    }
}

You could also use a ThreadPool thread, if that is more to your taste - the best choice depends on how much control you need over the thread.

like image 149
McKenzieG1 Avatar answered Sep 29 '22 08:09

McKenzieG1