2008-09-30 36 views
9

我试图找出是否有一种方法可靠地确定何时托管线程即将终止。我正在使用包含对PDF文档支持的第三方库,问题是为了使用PDF功能,我必须显式初始化PDF组件,完成工作,然后在线程终止之前显式地初始化组件。如果未调用uninitialize,则会引发异常,因为未被正确释放非托管资源。由于线程类是密封的并且没有事件,所以我必须将线程实例包装到一个类中,并且只允许此类的实例完成这项工作。有没有办法确定.NET线程何时终止?

我应该指出,这是多个Windows应用程序使用的共享库的一部分。我可能并不总是能够控制调用这个库的线程。由于PDF对象可能是对该库的调用的输出,并且由于调用线程可能会对该对象执行一些其他的工作,所以我不想立即调用清理函数;我需要在线程终止之前尝试去做。理想情况下,我希望能够订阅诸如Thread.Dispose事件之类的内容,但这就是我所缺少的。

回答

1

我想你可以使用[自动|手动] ResetEvent,当线程终止

3

你不想换System.Thread本身 - 只是你PDFWidget类是做工作的组成是:

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(); 
    } 
} 

你也可以使用一个线程ThreadPool,如果更符合你的口味 - 最好的选择取决于你在线程上需要多少控制。

0

难道你不只是将你的PDF使用情况与一个finally(如果它是一个单一的方法),或在一个IDisposable?

1

如何在异步模式下调用标准方法? e.g

//declare a delegate with same firmature of your method 
public delegete string LongMethodDelegate(); 

//register a callback func 
AsyncCallback callbackFunc = new AsyncCallback (this.callTermined); 

//create delegate for async operations 
LongMethodDelegate th = new LongMethodDelegate (yourObject.metyodWichMakeWork); 

//invoke method asnync. 
// pre last parameter is callback delegate. 
//the last parameter is an object wich you re-find in your callback function. to recovery return value, we assign delegate itSelf, see "callTermined" method 
longMethod.beginInvoke(callbackFunc,longMethod); 

//follow function is called at the end of thr method 
public static void callTermined(IAsyincResult result) { 
LongMethodDelegate method = (LongMethodDelegate) result.AsyncState; 
string output = method.endInvoke(result); 
Console.WriteLine(output); 
} 

看到这里形成更多的信息:http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx

1

有很多方法可以做到这一点,但最简单的是做这样McKenzieG1说,只是包裹调用PDF库。在线程中调用PDF库后,您可以使用Event或ManualResetEvent,具体取决于您需要等待线程完成的方式。

如果您使用事件方法,请不要忘记使用BeginInvoke将事件调用封送到UI线程。

相关问题