首页 文章

有没有办法确定.NET线程何时终止?

提问于
浏览
9

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

我应该指出,这是多个Windows应用程序使用的共享库的一部分 . 我可能无法始终控制线程调用此库 .

由于PDF对象可能是对此库的调用的输出,并且由于调用线程可能会对该对象执行其他一些操作,因此我不想立即调用清理函数;我需要尝试在线程终止之前做到这一点 . 理想情况下,我希望能够订阅Thread.Dispose事件,但这就是我所缺少的 .

7 回答

  • 1

    http://wintellect.com查看Powerthreading库 .

  • 1

    你不想自己包装 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 线程,如果这更符合您的口味 - 最佳选择取决于您对线程需要多少控制权 .

  • 1

    我想你可以使用线程终止时设置的[Auto | Manual] ResetEvent

  • 1
  • 0

    如何在异步模式下调用标准方法?例如

    //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

  • 0

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

    如果您正在使用Event方法,请不要忘记使用BeginInvoke封送到UI线程的事件调用 .

  • 3

    难道你不是只用last(或者是单个方法)或者在IDisposable中包装你的PDF用法吗?

相关问题