有没有一种方法可以确定.NET线程何时终止?

时间:2020-03-06 14:55:25  来源:igfitidea点击:

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

我应该指出,这是多个Windows应用程序使用的共享库的一部分。我可能并不总是控制对这个库进行调用的线程。

由于PDF对象可能是对该库的调用的输出,并且由于调用线程可能对该对象进行了其他工作,所以我不想立即调用cleanup函数;我需要尝试在线程终止之前立即执行操作。理想情况下,我希望能够订阅诸如Thread.Dispose事件之类的东西,但这就是我所缺少的。

解决方案

我认为我们可以使用[Auto | Manual] ResetEvent,该方法将在线程终止时设置

捕获ThreadAbortExcpetion。

http://msdn.microsoft.com/zh-CN/library/system.threading.threadabortexception.aspx

我们本身不想包装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线程,如果我们更喜欢该线程,则最佳选择取决于我们需要对该线程进行多少控制。

我们是否只用finally(如果是单个方法)或者用IDisposable来包装PDF使用情况?

在http://wintellect.com上检查Powerthreading库。

在异步模式下调用标准方法该怎么办?
例如

//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/zh-cn/library/2e08f6yc.aspx

我们可以通过多种方法来执行此操作,但是最简单的方法是按照McKenzieG1的说明进行操作,然后将调用包装到PDF库中。在线程中调用PDF库之后,可以根据需要等待线程完成的方式使用Event或者ManualResetEvent。

如果我们使用的是Event方法,请不要忘记使用BeginInvoke将事件调用封送给UI线程。