【问题标题】:How to abort a thread that runs unmanaged code如何中止运行非托管代码的线程
【发布时间】:2017-01-04 20:21:23
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# multithreading unmanaged


    【解决方案1】:

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

    类似这样的:

     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:我不知道这是否是一个糟糕的解决方案,但它对我有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 2010-12-10
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 2011-01-29
      相关资源
      最近更新 更多