I have a long running function in a C++-DLL. I start this function from C#-code. In C#-code I call the function in an own thread.
Now I want to abort the thread. The ThreadAbortException
occurs. The native function stops. But I'm not able to catch the Exception. The necessary code in the catch
clause is never executed.
Here is the code how I call the native function:
[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
}
}
And here is the code how I handle the thread:
object value = null;
Thread thread = new Thread(
() =>
{
value = ThreadProc();
});
thread.Start();
thread.Join();
errorCode = (int)value;
with ThreadProc:
public void ThreadProc()
{
_errorCode = LongRunningFunction();
}
How is it possible to handle the exception? When the exception occurs the errorCode is not 2001 but 0. But I need 2001 as return value.