0

我在 C++-DLL 中有一个长时间运行的函数。我从 C# 代码开始这个函数。在 C# 代码中,我在自己的线程中调用该函数。

现在我想中止线程。ThreadAbortException发生。本机功能停止。但我无法捕捉到异常。catch子句中的必要代码永远不会执行。

这是我如何调用本机函数的代码:

    [DllImport(DllFileName, CallingConvention = CallingConvention.StdCall, EntryPoint = "LongRunningNativeFunction", CharSet = CharSet.Ansi)]
    [return: MarshalAs( UnmanagedType.I4 )]
    public static extern int LongRunningNativeFunction();

    public static int LongRunningFunction()
    {
        try
        {
            int ret = LongRunningNativeFunction(); // <== here occurs the exception
            return ret;
        }
        catch ( System.Threading.ThreadAbortException e )
        {
            // THIS DOES NOT CATCH THE EXCEPTION
            return 2001; // <== this never happens, but it should
        }
    }

这是我如何处理线程的代码:

            object value = null; 
            Thread thread = new Thread(
                () => 
                {
                    value = ThreadProc();
                });
            thread.Start();
            thread.Join();
            errorCode = (int)value;

使用 ThreadProc:

        public void ThreadProc()
        {
            _errorCode = LongRunningFunction();
        }

如何处理异常?发生异常时,errorCode不是2001 而是 0。但我需要 2001 作为返回值。

4

0 回答 0