2008-09-30 83 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線程。

相關問題