user371602
user371602

Reputation: 13

cleaning up unmanaged c++ thread on c# application exit

Here's my setup:
1) c# application starts up and calls an exported unmanaged c++ dll function
2) the dll function spawns a thread via win32 CreateThread
3) this new thread does it's "work" in a while loop, checking for an exit flag

When I exit the c# application, the thread exits immediately.

Questions:
1) What can I do to allow my thread to cleanup before exiting?

Much thanks - I am new to the c# world, but experienced with c++

Upvotes: 1

Views: 707

Answers (1)

Cory Nelson
Cory Nelson

Reputation: 29981

When your C# app exits:

  1. Set a flag visible to the thread.
  2. Call WaitForSingleObject on the HANDLE returned by CreateThread. This will make it wait for the thread to exit.
  3. Optionally be a good citizen and call CloseHandle on the thread's HANDLE to free its resources, though this doesn't really matter if the app is about to exit.
  4. Periodically check this flag inside your thread to see if it should exit the loop.

Upvotes: 2

Related Questions