views:

141

answers:

3

Here's my problem: I have an unmanaged dll that I made.I'm calling one of this dll's functions in my C# code, using PInvoke. Under certain conditions, in the dll function, I want to be able to terminate the thread that is running the function.How would I achieve that?

Sorry if it is a stupid question, but I'm a total noob when it comes to threading:)

+2  A: 

If I understand you correctly, your situation is like this (using Pseudocode for brevity)

C#
==

Main()
{
   StartNewThread(MyThread);
   DoStuff();
}

MyThread()
{
    UnmanagedDll.DoSomething();
}

Unmanaged DLL
=============
DoSomething()
{
    // Does something here
}

Is that correct?

If so, returning from UnmanagedDll.DoSomething() will cause the calling thread to terminate if there are no statements after the call to UnmanagedDll.DoSomething(). So, just return control back to the C# program.

If that's not your situation, please provide more details.

Eric J.
+3  A: 

Man, that sounds dangerous. Why terminate the thread? You might be in a thread you don't own depending on how you're marshalling the call. Either ways, it seems like your best option is to return something to indicate you want to terminate the thread and have the managed code handle it gracefully. Don't try to kill the thread in native code.

psychotik
A: 

I would pass back a special result from the unmanaged DLL function and (having detected the special return value) terminate the thread in C#. Terminating it in the DLL sounds like a really bad idea to me.

Scott Smith