如何中止运行非托管代码的线程

本文关键字:线程 非托管代码 运行 何中止 | 更新日期: 2023-09-27 18:15:32

我正在开发一个多线程应用程序。

我的一个线程运行非托管代码,当非托管代码引发异常时,thread.Abort()不做任何操作。运行将在thread . abort()行停止。

在c#中我如何中止运行非托管代码的线程?

如何中止运行非托管代码的线程

我也遇到过类似的问题。假设您的线程正在运行非托管代码和托管代码,我建议您有一个标志,并且托管代码中的线程中止其自身。

像这样:

 private Thread thread1 = null;
 private bool thread1Abort = false;
 private void KillAllThreads() {
        if (thread1 != null && thread1 .IsAlive)
            thread1Abort = true;
 }
 private void function1() {
    try {
            if (mDocumentGroupThreadAbort) {
                mDocumentGroupThreadAbort = false;
                //Is you want to restart the thread may be a problem using abort. Thread will raise an error because the abort is not concluded.
                //mDocumentGroupThread.Abort();
                return;
            }
            //function with unmanaged code...
    } catch (System.Threading.ThreadAbortException) {
            ....
    } finally {
            ...
    }
}
static void Main(){
    this.thread1 = new Thread(() => {
            function1();
        });
    this.thread1.Start();
    Console.Readline();
}

PS:我不知道这是不是一个糟糕的解决方案,但它对我来说很有效